I am trying to connect to an oracle database with Python code. I am using the OracleDB package but want it so that the user is able to connect to the DB with their own password machine and password rather than coding it into the code itself.
So far I have this,
import oracledb
import os
username=os.environ.get("Username")
pw=os.environ.get("pasword")
conn = oracledb.connect(user=username, password=pw, host="url", port=0000, service_name="service"
Source the environment variables (Make them available to the python process)
$cat env.sh
export USERNAME=app_schema
export PASSWORD=secret
$cat connect.py
import oracledb
import os
username=os.environ.get("USERNAME")
pw=os.environ.get("PASSWORD")
conn = oracledb.connect(user=username, password=pw, host="localhost", port=1521, service_name="XEPDB1")
c = conn.cursor()
c.execute('select dummy from dual')
for row in c:
print (row[0])
conn.close()
$ # source the variables (note the dot)
$. env.sh
$python connect.py
X
Best of luck!
Related
I am try to connect to my gaussdb or even postgressql using in python jaydebeapi from linux
and i keep get error
Class name not found
I copy my jar file to /usr/lib/jvm/java-11-openjdk-amd46/lib/com.driver.jar
is there something else ?
‘’’
import jaydebeapi
import sys
jaydebeapi.connect("com.gauss.Driver",
url, [username, password], "./file-jdbc.jar")
Erorr Class com.gauss.driver not found
‘’’
You can try to explicitly start a JVM and pass it the fullpath of your driver jar file:
import jaydebeapi
import jpype
jpype.startJVM(jpype.getDefaultJVMPath(),
f"-Djava.class.path=/usr/lib/jvm/java-11-openjdk-amd46/lib/com.driver.jar")
jaydebeapi.connect("com.gauss.Driver", url, [username, password], "/usr/lib/jvm/java-11-openjdk-amd46/lib/")
If you're using postgresSQL databases I would also suggest you to take a look to the psycopg library:
https://pypi.org/project/psycopg/
https://www.geeksforgeeks.org/introduction-to-psycopg2-module-in-python/
I'm trying to get a code scheduled in windows:
import requests
from datetime import date
import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine
server= 'xxxxx'
database='xxxxx'
driver_sql= 'ODBC Driver 17 for SQL Server'
database_con= f'mssql://#{server}/{database}?driver={driver_sql}'
engine= sqlalchemy.create_engine(database_con)
connection = engine.connect()
adr='https://api.swaggystocks.com/wsb/sentiment/ticker'
r = requests.get(adr)
json = r.json()
pdbasses= pd.DataFrame(json["data"])
pdbasses["timestamp"] = pd.to_datetime("today")
pdbasses["timestamp"] = pdbasses["timestamp"].dt.strftime("%Y-%m-%d")
pdbasses.to_sql("swaggy", connection, if_exists='append',index=False)
direct =r'D:\SQL\getdatafromhere\file'+str(date.today())+".csv"
pdbasses.to_csv(direct, index=False)
the problem is, when I put it through pyinstaller it says I'm missing packages that I can't even install via pip MySQLdb,Psycob2 etc.
Then when the exe file gets put out, I run it and it just blips for a second and doesn't do anything. The code works in PyCharm. I tried running pyinstaller through pycharm, but I get a Linux exe file/spec file. I tried converting that one to an exe file, but still doens't work.
Thank you for your time
I have VBA code calling a Python script that works on my PC.
The Python code uses SQL Alchemy to create an Engine, connects to a database, binds the session and retrieve data using a SELECT * FROM basic query. After it reads it, the data is sent to an xlsx file.
Python code with some minor changes for security reasons:
# import dependencies
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
import pandas as pd
import os
import cx_Oracle
# Creating engine connection
engine = create_engine('oracle://user:pw#IP:Port/Schema')
# Binding session
session = Session(bind=engine)
# Indicating path for Oracle client 64bits
lib_dir = r"Full_Path\instantclient_19_9"
try:
cx_Oracle.init_oracle_client(lib_dir=lib_dir)
except Exception as err:
print("Error connecting: cx_Oracle.init_oracle_client()")
print(err);
sys.exit(1);
# read sql a run query
data = pd.read_sql("SELECT * FROM Schema.V_FLUJOS_SOLICITADOS", engine)
# save path
path = r'Another_Full_Path'
# save dataframe into csv
data.to_excel(os.path.join(path, r'Flow extraction.xlsx'), index = False)
For this code, I need to tell Python where to find the Oracle client of 64 bits because my company has its database connected to a PowerBuilder program that can only use 32 bit, so I just can't change the installation, that's why I re-route.
VBA code:
Sub runScript()
Application.ScreenUpdating = False
teoricos = ThisWorkbook.Name
Dim Ret_Val
user = Environ("UserName")
Select Case user
Case "USER1"
python_route = "C:\Users\USER1\Anaconda3\python.exe"
Case "USER2"
python_route = "C:\Users\USER2\Anaconda3\python.exe"
End Select
args = """Full_path\V_FLUJOS_SOLICITADOS.py"""
Ret_Val = Shell(python_route & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub
The code works on my PC (User 1), but it doesn't on my partner's PC.
What I've done so far:
Installed cx_Oracle on her machine
Tested the whole code on Jupyter Notebook of her machine and it worked
Tested full access to all paths
Activated the Microsoft Shell Reference in VBA
The VBA code on her PC runs, but it just opens the command window really fast and it closes.
On my PC it takes from 3 to 5 seconds to do the whole thing, so I can see the CMD for just a bit there (and also check that the file updated which is the most clear indicator that it worked).
I have some script in Python which are executed by crontab on Raspbian.
I use the MySQLdb library for request in the local network.
All scripts work fine if i launch them directly, by Python-IDLE, or in the console.
But if they are launched by cron, those who just execute "INSERT" requests work, but those who execute "SELECT" request don't work.
I haven't found a clear solution, but it seems that crontab doesn't execute the same configuration of the SQL client as the user.
Maybe i have to change the path before all request ? (looking for a "./my.cnf" ?
tested with library MySQLdb and PyMySQL
#! /usr/bin/python
# -*- coding: utf-8 -*-
# importations
import os
import time
import sys
import pymysql as sql # or MySQLdb as...
from os import path as os_path
#-----------------------------------------------------------------#
# constants : use your own values / utilisez vos propres valeurs #
#-----------------------------------------------------------------#
PATH_THERM = "/home/pi/Documents/" #path to this script
DB_SERVER ='192.168.0.59' # MySQL : IP server
DB_USER='user' # MySQL : user
DB_PWD='password' # MySQL : password
DB_BASE='capteurs' # MySQL : database name
def log(texte):
datation = time.strftime('%d-%m-%Y %H:%M:%S')
logue = open('log_test.txt','a')
txt = "\n" + datation + "\t" + texte
txt = txt.encode('utf-8')
logue.write(txt)
logue.close()
def query_temp():
datebuff = time.strftime('%d-%m-%Y')
db = sql.connect(DB_SERVER, DB_USER, DB_PWD, DB_BASE)
cursor = db.cursor()
cursor.execute("""SELECT sonde2,date FROM `PiTemp` ORDER BY date DESC LIMIT 0, 1""")
rows = cursor.fetchall()
print datebuff, u" : Dernière température de l'eau :", rows[0][0], u"°C"
log(u"lecture température SQL - ok")
a = rows[0][0]
b = rows[0][1]
return (a, b)
#----------------------------------------------------------#
# principal code #
#----------------------------------------------------------#
PATH=os_path.abspath(os_path.split(__file__)[0])
os.chdir(PATH)
log('start')
log(PATH)
txt = str(query_temp()[0])
log(txt)
crontab :
*/1 * * * * python /home/pi/Documents/180623_test.py
Found raeson of fail, the print passed by cron don't encode/decode the same as the console (!??).
... print (u"Alerte, tous à poil !") UnicodeEncodeDecode Error !
Strange, looks like cron doesn't encode / decode the same than the user.... (!?)
Solved with no latin characters in print, or print passed by try/except...
I'm using pyodbc to connect to Vertica.
I've installed Vertica driver, unixodbc and pyodbc.
Now I have problem with executinq unicode queries.
con = pyodbc.connect('Driver={driver};Servername={server};Port={port};Database={db};UserName={user};password={password}'.format(...))
cur = con.cursor()
cur.execute('SELECT * FROM table') # It works
cur.execute(u'SELECT * FROM table') # It fails
The error is:
ProgrammingError: ('42601', '[42601] ERROR 4856: Syntax error at or near " (4856) (SQLExecDirectW)')
Looks like wrong encoding defined in vertica.ini file(or wrong locale setting in odbc.ini)
vertica.ini
[Driver]
DriverManagerEncoding=UTF-16
...
odbc.ini
...
Locale = en_US#collation=binary
...
I bet on vertica.ini. I have no MacOS to check, but by docs you need to define UTF-32. Can you post your vertica.ini abd odbc.ini + database locale?
HP Vertica
daniel=> show locale;
name | setting
--------+--------------------------------------
locale | en_US#collation=binary (LEN_KBINARY)
(1 row)
For more info read here.
What version of pyodbc and python you are using? What OS?
try using first line in your python code as # -- coding: utf-8 --?
and update pyodbc
sudo pip install --upgrade pyodbc