SQL Database file not showing up in folder? - python

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.

Related

Error while connecting with Oracle 12c using cx_oracle

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()

Python with psycopg2 and pgAdmin4 how can i retrieve bytea data

I have uploaded a jpg image with the bytes() function to the bytea field.
INSERT CODE
conn = None
try:
# read data from a picture
imagen = open("imagen.jpg", "rb").read()
# connect to the PostgresQL database
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute("INSERT INTO nuevotest(id,data) " +
"VALUES(%s,%s)",
(1, bytes(imagen)))
# commit the changes to the database
conn.commit()
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
SELECT CODE:
conn = None
try:
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute(""" SELECT data
FROM nuevotest
WHERE id=1 """,
)
# commit the changes to the database
conn.commit()
imagen = cur.fetchall()
print(type(imagen))
print(imagen)
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
But what i was expectiong was a list or tuple with the byte code, not this:
PyCharm console with a (memory direction? idk)
I have no idea how to work with that.
Depends on what you are planning on doing after you retrieve the data. As #adrian_klaver said, you can use a buffer to write the output. Like this you would send it to a file:
with open(your_output_file, 'wb') as im:
im.write(the_in_memory_data)
Using PIL you can output it to the image viewer of the system without saving it.

Call a MySQL stored procedure from Python unattended

I need to call a MySQL stored procedure from Python, and I don't need to wait for the procedure to finish.
How can this be done?
code below work for me
import mysql.connector
def insertComment(ecID, eID, eComment):
try:
contraseƱa = input("Please, enter your database password: ")
connection = mysql.connector.connect(host='localhost',
database='mantenimiento',
user='hernan',
password=contraseƱa,
port=3309)
if connection.is_connected():
cursor = connection.cursor(prepared=True)
procedure = "call mantenimiento.spSaveComment(%s, %s, %s)"
datos = (ecID, eID, eComment)
cursor.execute(procedure, datos)
# datos = [(ecID, eID, eComment)] # Tuple for executemany
# cursor.executemany(procedure, datos)
connection.commit()
print(cursor.rowcount, "Comment inserted sucessfully")
except mysql.connector.Error as error:
connection.rollback()
print("Failed to insert value into database {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("Server connection was closed")
insertComment(15, 25, 'Test MariaDB or MySQL SP from python')
One possible solution is by using celery: "Celery is an asynchronous task queue/job queue based on distributed message passing.". You can create a task where you call your MySQL store procedure.

python mysql connection auto connect on error

I have a problem with my python mysql connection which I need help with.
My setup is two Pi's running servers on each one. One Pi (SolartPi) has Mysql database collecting data. The other pi (OfficePi) is connecting to the solarPi database to retrieve and update data over a network connection.
My main script works all ok until I have to reboot the SolarPi for a maintenance or power problem and the connection to the OfficePi is lost. The python script on the officePi then goes into a fault loop "2006, MYSQL Server has gone away" Below is a sample of this script.
import MySQLdb
connSolar = MySQLdb.connect("192.xxx.x.x", "external", "xxxxx", "xxxxx")
#eternal connection to solar pi database
cursSolar = connSolar.cursor()
while 1:
try:
cursSolar.execute("SELECT * FROM dashboard")
connSolar.commit()
for reading in cursSolar.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
connSolar.close()
So I tried rewriting this with the script from stackoverflow and a web site as shown below, but this now terminates the program when SolarPi is rebooted with the following error
_mysql_exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on \'192.xxx.x.x' (111 "Connection refused")')
import MySQLdb
class DB:
con = None
def connect(self):
self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house") #eternal connection to solar pi database
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
while 1:
db = DB()
sql = "SELECT * FROM dashboard"
cur = db.query(sql)
for reading in cur.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand
Is there a way for the OfficePi to keep trying to connect to SolarPi mysql database when it has shut down.
Change your code to check a valid connection each loop otherwise pass:
import MySQLdb
class DB:
def connect(self):
try:
self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house")
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
self.conn = None
return self.conn
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
while 1:
db = DB()
conn = db.connect()
if conn:
sql = "SELECT * FROM dashboard"
cur = db.query(sql)
for reading in cur.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand

connect to mysql in a loop

i have to connect to mysql server and grab some data for ever
so i have two way
1)connect to mysql the grab data in a while
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
while True:
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
sleep(0.5)
this working good but if script crashed due to mysql connection problem script goes down
2)connect to mysql in while
while True:
try:
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
cursor.close()
conn.close()
sleep(0.5)
except:
print("recoverable error..")
both code working good but my question is which is better?!
Among these two, better way will be to use a single connection but create a new cursor for each statement because creation of new connection takes time but creating a new cursor is fast. You may update the code as:
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
while True:
try:
cursor = conn.cursor(buffered=True)
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
except Exception: # Catch exception which will be raise in connection loss
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
finally:
cursor.close()
conn.close() # Close the connection
Also read Defining Clean-up Actions regarding the usage of try:finally block.

Categories