Error while connecting with Oracle 12c using cx_oracle - python

I am trying to connect with an Oracle 12c database using cx_oracle. My code is listed below:
import cx_Oracle
from cx_Oracle import DatabaseError
import pandas as pd
import credaws
import os
os.system('export ORACLE_HOME=/opt/app/oracle/product/client_12_2')
os.system('export PATH=$ORACLE_HOME/bin:$PATH')
os.system('export LD_LIBRARY_PATH=$ORACLE_HOME/lib')
try:
# cx_Oracle.init_oracle_client(lib_dir=libdir)
dsn_tns=cx_Oracle.makedsn(credaws.host_name,credaws.port_number,service_name=credaws.service_name)
conn = cx_Oracle.connect(user=credaws.user,password=credaws.password,dsn=dsn_tns)
if conn:
cursor = conn.cursor()
print('Connection Successful')
except DatabaseError as e:
err, = e.args
print("Oracle-Error-Code:", err.code)
print("Oracle-Error-Message:", err.message)
finally:
cursor.close()
conn.close()
I'm still getting this error:
Oracle 12c is installed in /opt/app/oracle/product/client_12_2 location. What am I doing wrong?
Edit 1: I setting ORACLE_HOME, PATH and LD_LIBRARY_PATH environment variables before calling cx_oracle connect method. However, still getting the same error.
Edit 2: When running this script as oracle user, I'm getting below error:

This question just assisted me big time. I have been struggling to connect to Oracle Database for a while. I just passed in the connection string directly to connect to the database and it worked. It is risky but the script is for my personal use. I new to python.
Here is my code.
import os
import cx_Oracle
os.system('set ORACLE_HOME=C:\\oraclexe\\app\\oracle\\product\\10.2.0\\server')
os.system('set PATH=$ORACLE_HOME/bin:$PATH')
os.system('set LD_LIBRARY_PATH=$ORACLE_HOME/lib')
#Test to see if the cx_Oracle is recognized
print(cx_Oracle.version) # this returns 8.2.1
cx_Oracle.clientversion()
# I just directly passed in the connection string
con = cx_Oracle.connect('USERNAME/PWD#SERVER:PORT/DATABASENAME')
cur = con.cursor()
try:
# test the connection by getting the db version
print("Database version:", con.version)
cur.execute("select * from products order by 1")
res = cur.fetchall()
print('Number of products is ',len(res))
for row in res:
print(row)
except cx_Oracle.DatabaseError as e:
err, = e.args
print("Oracle-Error-Code:", err.code)
print("Oracle-Error-Message:", err.message)
finally:
cur.close()
con.close()

Related

SQL Database file not showing up in folder?

I am trying to create a database file using the following code:
def dbconnect():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
sqlite_select_Query = "select sqlite_version();"
cursor.execute(sqlite_select_Query)
record = cursor.fetchall()
print("SQLite Database Version is: ", record)
cursor.close()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
conn = dbconnect()
conn.close()
yet when I run the code, although there are no file errors, it doesnt print anything or create a SQL file in the folder of the python code.
I can't seem to figure out what is going wrong.

Error while connecting to MySQL Not all parameters were used in the SQL statement

I can't establish connection to my Databases because I'm apparently missing an SQL statement, but I don't know where it is. Pls Help.
import mysql.connector as msql
from mysql.connector import Error
import pandas as pd
db123 = msql.connect(host='localhost', port='7616', user='root', password='admin#123')#give ur username, password
empdata = pd.read_csv('C:\\Users\\me\\Desktop\\Goods.csv', index_col=False, delimiter=',', low_memory=False)
empdata.head()
try:
if db123.is_connected():
cursor = db123.cursor()
for i,row in empdata.iterrows():
sql = """INSERT INTO mynewsystem.products(Barcode, Prod_Name, Price) VALUES (%s,%s,%s)"""
cursor.execute(sql, tuple(row))
print("Record inserted")
db123.commit()
except Error as e:
print("Error while connecting to MySQL", e)

How to fetch data from SQL query in Python

Good Afternoon,
I wrote a query in MySQL, and I want to execute the same query in Python.
The Code I wrote as Follows.
1.
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='AdventureWorks2012',
user='root',
password='r##*****')
sql_select_Query = "select * from Person.person"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
However, I'm getting following error message while running part two-
''File "", line 5
password='r##*****')
^
SyntaxError: unexpected EOF while parsing''
Any suggestion please how to overcome this problem?
You are missing the except clause:
try:
connection = mysql.connector.connect(host='localhost',
database='AdventureWorks2012',
user='root',
password='r##*****')
except Exception as e:
print(e)
You should check the documentation for more information.

ImportError: cannot import name 'config' & 'module' object is not callable using PostgreSQL & Python

Hey I am having trouble connecting to my PostgreSQL DB through Python. I am following this tutorial However when I attempt to run the code I return the following error:
Traceback (most recent call last):
File "/Users/username/Desktop/Coding/anybody/postgresqltest.py", line 2, in <module>
from config import config
ImportError: cannot import name 'config'
[Finished in 0.201s]
However, I have pip installed config (I am using a virtual environment) and verified using pip list
When I remove from config import config and replace with just import config I receive this error:
module' object is not callable [Finished in 0.127s]
Here is the code I have written, I am a bit stuck on what to do next (the actual database I am connecting to isn't called test btw, this is a different one):
import psycopg2
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
from config import config
def connect():
conn = None
try:
params = config()
print('Connecting to the PostgreSQL DB')
conn = psycopg2.connect(**params)
cur = conn.cursor()
print('PostgreSQL database version:')
cur.execute('Select version()')
db_version = cur.fetchnone()
print(db_version)
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
Put the config function into a separate .py file.
actually you don't need the config module at all in case you have the DB connection parameters:
here's the code that worked for my connection to DB hosted by Elephant (https://api.elephantsql.com/):
import psycopg2
#from config import config
conn = None
conn = psycopg2.connect(
host="your DB host",
database="DB NAME",
user="USER NAME",
password="DB PASSWORD")
try:
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
# create a cursor
cur = conn.cursor()
# execute a statement with cur.execute()
# in this case we get the version
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
main()
also, the docs by psycopg don't mention "config" module:
https://www.psycopg.org/docs/usage.html

PyMySQL Error inserting values into table. - Python

I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module.
#!python3
import pymysql, sys, time
try:
print('Connecting.....')
time.sleep(1.66)
conn = pymysql.connect(user='root', passwd='root', host='127.0.0.1', port=3306, database='MySQL')
print('Connection suceeded!')
except:
print('Connection failed.')
sys.exit('Error.')
cursor = conn.cursor()
sql = "INSERT INTO login(USER, PASS) VALUES('test', 'val')"
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
print('Operation failed.')
conn.close()
I think it may have to do with the order of the statements in the connection. According to the PyMySQL github (found here) the correct order is host, port, user, passwd, db.
Like this :
user = input("User: ")
pass = input("Pass: ")
sql = "INSERT INTO login(USER, PASS) VALUES('%s', '%s')"%(user, pass)
btw you should connect like this :
conn = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
db='MySQL
)

Categories