Python: cx_Oracle cursor.execute() hangs on UPDATE query - python

I have looked at similar questions but nothing has worked for me so far
So here it is. I want to update my table through a python script. I'm using the module cx_oracle. I can execute a SELECT query but whenever I try to execute an UPDATE query, my program just hangs (freezes). I realize that I need to use cursor.commit() after cursor.execute() if I am updating a table but my code never gets past cursor.commit(). I have added a code snippet below that I am using to debug.
Any suggestions??
Code
import cx_Oracle
def getConnection():
ip = '127.0.0.1'
port = 1521
service_name = 'ORCLCDB.localdomain'
username = 'username'
password = 'password'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name) # (CONNECT_DATA=(SERVICE_NAME=ORCLCDB.localdomain)))
return cx_Oracle.connect(username, password, dsn) # connection
def debugging():
con = getConnection()
print(con)
cur = con.cursor()
print('Updating')
cur.execute('UPDATE EMPLOYEE SET LATITUDE = 53.540943 WHERE EMPLOYEEID = 1')
print('committing')
con.commit()
con.close()
print('done')
debugging()
**Here is the corresponding output: **
<cx_Oracle.Connection to username#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLCDB.localdomain)))>
Updating
Solution
After a bit of poking around, I found the underlying cause! I had made changes to the table using Oracle SQL Developer but had not committed them, when the python script tried to make changes to the table it would freeze up because of this. To avoid the freeze, I committed my changes in oracle sql developer before running the python script and it worked fine!

Do you have any option to look in the database ? I mean , in order to understand whether is a problem of the python program or not, we need to check the v$session in the database to understand whether something is blocked.
select sid, event, last_call_et, status from v$session where sid = xxx
Where xxx is the sid of the session which has connected with python.
By the way, I would choose to commit explicitly after cursor execute
cur.execute('UPDATE EMPLOYEE SET LATITUDE = 53.540943 WHERE EMPLOYEEID = 1')
con.commit()
Hope it helps
Best

Related

How to commit stored procedure execution by using pyodbc

I am trying to execute stored procedure by using pyodbc in databricks, after executing SP I tried to commit the connection but, commit is not happening. Here I am giving my code, please help me out from this issue.
import pyodbc
#### Connecting Azure SQL
def db_connection():
try:
username = "starsusername"
password = "password-db"
server = "server-name"
database_name = "db-name2"
port = "db-port"
conn=pyodbc.connect('Driver={ODBC Driver 17 for SQL server};SERVER=tcp:'+server+','+port+';DATABASE='+ database_name +';UID='+ username +';PWD='+ password)
cursor=conn.cursor()
return cursor, conn
except Exception as e:
print("Faild to Connect AZURE SQL: \n"+str(e))
cursor, conn = db_connection()
# conn1.autocommit=True
cursor.execute("delete from db.table_name")
cursor.execute("insert into db.table_name(BUSINESS_DATE) values('2021-10-02')")
cursor.execute("exec db.SP_NAME '20211023'")
conn.commit()
conn.close()
here I am commiting connection after SP excution. deletion and insertion is not happening at all. and I tried with cursor.execute("SET NOCOUNT ON; exec db.SP_NAME '20211023'") but it's also not working.
Thanks in Advance
If you check this document on pyodbc, you will find that -
To call a stored procedure right now, pass the call to the execute method using either a format your database recognizes or using the ODBC call escape format. The ODBC driver will then reformat the call for you to match the given database.
Note that after connection is set up or done, try doing conn.autocommit = True before calling your SP and it will help. By default it is false.
Executing the Stored Procedure.
You will be able to execute your stored procedure if you follow the below code snippet.
cursor = conn.cursor()
conn.autocommit = True
executesp = """EXEC yourstoredprocedure """
cursor.execute(executesp)
conn.commit()
Delete the Records in SQL Server
You can delete record as shown in the below example.
...#just an example
cursor.execute('''
DELETE FROM product
WHERE product_id in (5,6)
''')
conn.commit()
Don’t forget to add conn.commit() at the end of the code, to ensure that the command would get executed.
Insert record in SQL Server
The below snippet show how we can do the same.
...#just an example
cursor.execute("INSERT INTO EMP (EMPNO, ENAME, JOB, MGR) VALUES (535, 'Scott', 'Manager', 545)")
conn.commit()
I will suggest you to read the for following document for more information.
Delete Record Documentation.
Insert Record Document

Python SQL Script - How to send email with error

I've built a Python script that runs a report for me using one of our vendor's API's, then uploads the data directly to an MS SQL server. I would like to add an error handler that sends an email when the insert fails for any reason.
Can I just wrap my insert statement in a try? Currently I have this going to a local server for testing...
conn = pyodbc.connect('Driver={SQL Server};'
'Server=localhost\*****local;'
'Database=Reporting;'
'Trusted_Connection=yes;')
#Set cursor variable
cursor = conn.cursor()
executeValue = """INSERT INTO New_Five9_CallLog
(Call_ID, [Timestamp],
Campaign, Call_Type, Agent_Email, Agent_Name, Disposition,
ANI, Customer_Name, DNIS, Call_Time, Rounded_Bill_Time,
Cost, IVR_Time, Queue_Wait_Time, QCB_Wait_Time,
Total_Queue_Time, Ring_Time, Talk_Time, Hold_Time, Park_Time,
ACW_Time, Transfers, Conferences, Holds, Parks, Abandoned,
Recordings, Handle_Time, Session_ID, IVR_Path,
Skill, Ticket_Number)
VALUES (""" + values + ")"
#Execute query
cursor.execute(executeValue)
#Commit and close
conn.commit()
conn.close()
I get the values variable with some other script above this section. What I'd like to know is how to capture an error on this section and then send an email to myself with the error description.
Check out this answer https://stackoverflow.com/a/42143703/1525867 explaining how to catch pyodbc specific errors (I personally use https://sendgrid.com/ to send emails)

Unknown Database Error python mysql

This link contains shows the database I've created in the mysql workbench and the connection I have established in the code but the database is unknown for some reason. Is there a step I've missed?
http://gyazo.com/d995c4da99043da43bfbd057a0a839c7
__author__ = 'avi'
from TwitterSearch import *
import json
twtsearch = TwitterSearch(
consumer_key='PXTUrlRfgC1zSTsAPU9z6EHtD',
consumer_secret='qM9F4FVj1qLFc6f795r96DQPNAJO8hkbWy4PXWYLfQcYyNGY7D',
access_token='2943116292-wVHEjbfjX7OFqaOURBqim5o7Vs6lZyjxsoto8nD',
access_token_secret='CJAppSRY9TZ5cwYTABZhH2YTd0rm5IzBDqPder6v4qLBA'
)
twtsearchorder = TwitterSearchOrder()
twtsearchorder.set_keywords(['iphone6'])
twtsearchorder.set_language('en')
twtsearchorder.set_include_entities(True)
tweet_limit=50
parsed_tweets= {}
table="twtinfo"
import MySQLdb as mdb
con = mdb.connect('localhost', 'root','root','tweetinfo')
cur=con.cursor()
for tweet in twtsearch.search_tweets_iterable(twtsearchorder):
if tweet_limit > 0 :
parsed_tweets['name'] = tweet['user']['screen_name']
parsed_tweets['content'] = tweet['text']
parsed_tweets['user_id'] = tweet['user']['id']
parsed_tweets['fav_count'] = tweet['favorite_count']
parsed_tweets['location'] = tweet['user']['location']
parsed_tweets['retweet_count'] = tweet['retweet_count']
placeholders= ', '.join(['%s'] *len(parsed_tweets))
columns = ', '.join(parsed_tweets.keys())
sql="INSERT into %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cur.execute(sql,parsed_tweets.values())
tweet_limit -= 1
The MySQL process is complaining about the database you are trying to access, namely tweetinfo isn't existing. MySQL error 1049 is usually an indication of having to forgot to select a database, but you did as forth argument to mdb.connect()
Possible errors could be:
That you have several MySQL processes running, with the one with the proper database not being on the default MySQL port.
That somehow your database GUI application hasn't actually submitted your database and table to the MySQL process.
That MySQL isn't running? You would probably get a different error message for that, but it could be an idea to make sure it is just in case.
Just to check if your tables exists and that your database is in place, open a terminal and write the following commands:
mysql -u root -proot
use tweetinfo;
show create table twtinfo;
Another thing to try could be to ask the MySQL process about which database it thinks you are using. Try adding something like the following to your code:
cur.execute("SELECT DATABASE() FROM DUAL;")
print("Database is: %s.", cur.fetchone()[0])
I'm not a python programmer, so I'm not entirely confident that will work without some adjustments.
If none of this gave you a good lead, I'm not quite sure what's wrong.

MySQL in Python

The purpose is to check if the email already exists in the database utilizing python and MySQLdb. I am using the variable mail to store the e-mail. The MySQL form is email. I have the code below:
if cursor.execute("select count(*) from registrants where email = " + "'"email2"'") == 0:
print "it doesn't exist!"
What is wrong with this statement or how can I go about doing this?
I hardly know where to start.
Just typing a string of SQL into a Python program doesn't somehow query the database. You actually have to open a database connection, instantiate a cursor, use that cursor to run the SQL, and fetch the result. All this is explained in the MySQLdb documentation.
Once you've done that, you'll still need to actually pass the email parameter from your form to the SQL statement, which you're not doing either.
well that won't work because that's just the mysql query string. You have to execute this query using a mysql client receive the results and the test. Using pymysql would be something like this:
import pymysql
connection = pymysql.connect(host,user,password,database)
cursor = connection.cursor()
cursor.execute("select count(*) from registrants where email = ?") #you need to replace the ? with some actual value or the query will fail
result = cur.fetchone()
if result[0]==0:
print "E-mail does not exist!"

MySQLdb python problem refresh database

I have wrote a python daemon for read a database... I do the next:
db.connect('localhost', user, pass, database)
while true:
cursor = db.cursor()
sql = "SELECT id FROM task WHERE status='pending'"
r = cursor.execute(sql)
if r != 0:
result = cursor.fetchall()
#.....
The problem is that: when change database, the daemon not detect it... can refresh...
what can I do??
thanks!!
This is just a guess since I don't have a full view of your code, but since you're connecting outside the loop any changes to database won't tell db to reconnect.
Again just a guess, not sure if you're threading or not threading, how the change coincides with the daemon... etc
I have soluted it activating commit at the end of the script:
db.autocommit(True)
thanks for all friends

Categories

Resources