How to fetch data from SQL query in Python - 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.

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.

Can't add (relatively) large amount of records with python to MySQL

I have a word_set with ~170k elements and want to save it to MySQL database. My code works with small amount (for example 5 or 10 records) but returns an error with larger amount:
2055: Lost connection to MySQL server at 'localhost:3306', system
error: 10054 Удаленный хост принудительно разорвал существующее
подключение
Code:
from mysql.connector import connect, Error
try:
with connect(
host='localhost',
user='root',
password='root',
port=3306,
database='scrabble',
# connection_timeout=20,
) as connection:
insert_vocabulary = """
INSERT INTO vocabulary
(word)
VALUES ( %s )
"""
vocabulary_records = []
for word in word_set:
record = (word,)
vocabulary_records.append(record)
with connection.cursor() as cursor:
cursor.executemany(insert_vocabulary,
vocabulary_records)
connection.commit()
except Error as e:
print(e)
I tried specify connection_timeout=20 but it doesn't change anything. Error occurs within a second, definitely not 20 seconds.
What am I doing wrong?

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 MYSQL doesn't work second time

Am receiving json data (from an other python script) to put inside MYSQL database, the code work fine the first time but the second time I got this error:
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
For troubleshooting am sending always the same data, but it still write an error the second time.
I tried also from information found on furums to place : cur = mydb.cursor() at diferents places but I have never been able to get this code work the second time.
There is my code :
import mysql.connector
import json
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="***"
)
def DATA_REPARTITION(Topic, jsonData):
if Topic == "test":
#print ("Start")
INSERT_DEBIT(jsonData)
def INSERT_DEBIT(jsonData):
cur = mydb.cursor()
#Read json from MQTT
print("Start read data to insert")
json_Dict = json.loads(jsonData)
debit = json_Dict['debit']
print("I send")
print(debit)
#Insert into DB Table
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
val=debit,
cur.execute(sql,val)
mydb.commit()
print(cur.rowcount, "record inserted.")
cur.close()
mydb.close()
Thanks for your help!
You only open your database connection once, at the start of the script, and you close that connection after making the first insert. Hence, second and subsequent inserts are failing. You should create a helper function which returns a database connection, and then call it each time you want to do DML:
def getConnection():
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="***")
return mydb
def INSERT_DEBIT(jsonData):
mydb = getConnection()
cur = mydb.cursor()
# Read json from MQTT
# rest of your code here...
cur.close()
mydb.close()

How to return errors from PYODBC

I'm making a connection to SQL Server to execute a stored procedure. What is the correct way to 'poll' the server to determine whether the stored procedure finished running successfully or returned an error if the SP takes longer than 60 seconds / 3600 seconds, etc?
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server}; SERVER=ServerName; PORT=1433;DATABASE=dbname;UID=%s;PWD=%s' % (username, password))
cnxn.execute("EXECUTE msdb.dbo.sp_start_job 'TestSP'")
<pyodbc.Cursor object at 0x0000000002D6DDB0>
How can I determine the status of the SP?
Consider wrapping the execute in a try/except to catch exceptions (which encompass errors). If no error is raised, execute is assumed to run correctly. Also, use the timeout variable (in seconds) as the database should raise OperationError if timeout occurs.
cnxn = pyodbc.connect('DRIVER={SQL Server}; SERVER=ServerName; PORT=1433; \
DATABASE=dbname;UID={0};PWD={1}'.format(username, password))
cnxn.timeout = 60
cursor = cnxn.cursor()
try:
cnxn.execute("EXECUTE msdb.dbo.sp_start_job 'TestSP'")
except Exception as e:
print(e)
It looks like you've skipped making a cursor, so you need to do that, then fetch the results. Try this:
import pyodbc
connection = pyodbc.connect('DRIVER={SQL Server}; SERVER=ServerName; PORT=1433;DATABASE=dbname;UID=%s;PWD=%s' % (username, password))
cursor = connection.cursor()
cursor.execute("EXECUTE msdb.dbo.sp_start_job 'TestSP'")
rows = cursor.fetchall()
for row in rows:
# Do stuff
print(row)

Categories