Inserting user data with stored procedure gives error when committing - python

This code gives an error on conn.commit line.
Error: ('HY000', "[HY000] [MySQL][ODBC 3.51 Driver]Commands out of sync; you can't run this command now (2014) (SQLEndTran)")
Whenever I call SP the ID is keep increasing in table but record is not inserting.
#app.route("/insert_user")
def insert_user():
try:
conn = pyodbc.connect("DRIVER={/usr/local/lib/libmyodbc3.so};SERVER=localhost;DATABASE=user_data;USER=user;PASSWORD=user_pass;OPTION=3;autoCommit = True")
cur = conn.cursor()
cur.execute("{call insert_user_sp(0,'aby#gmail.com','345','male','1992-01-12','www.facebook.com','abc','xyz','p','jr','english','i am student')}")
conn.commit()
except Error as e:
print e
finally:
cur.close()
conn.close()

Since you're using MySQL on Linux, I would recommend using a MySQL Python package rather than pyodbc. I use pyodbc for connecting to Microsoft SQL Server, but this package when using MySQL:
https://pypi.python.org/pypi/mysqlclient
Then you can use cursor.callproc():
http://mysqlclient.readthedocs.org/en/latest/user_guide.html?highlight=callproc#cursor-objects
Good luck!

Related

Python MySQL not reading from database

Python unable to read from MySql database. Connectivity works but no results returned
import mysql.connector
cnx = mysql.connector.connect(user='user', password='pwd',host='<host>', port='<port>',database='mydb')
cursor = cnx.cursor()
print("Connection success")
query = ("SELECT * from users")
cursor.execute(query)
for (row) in cursor:
print(row)
print("Print complete")
cursor.close()
cnx.close()
I get below result
Connection success
Print complete
If I add below line
rows=cursor.fetchall()
I get below error
InterfaceError: No result set to fetch from.
I have checked from MySql workbench and I get results from above query.
EDIT: The question is not about fetchall, even without fetchall I don't see any results.
EDIT 2:
Few Observations:
If I try with incorrect password, I get Access Denied error.
If I try with incorrect table name (with correct password) I get
error that table doesn't exist.
If I add below line before the for loop
print(len(cursor.description))
I get below error
TypeError: object of type 'NoneType' has no len()

1064 error while operating MySQL database with Python

I want to write a program in Python to control MySQL database, but the following error occurs
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; chec
k the manual that corresponds to your MySQL server version for the right syntax
to use near 'Code,type, number,Whether )VALUES ('cl8k-k520-fg45-d4sa-sd9k','n' at line 1")
Codeļ¼š
import pymysql
db = pymysql.connect("localhost", "root", "root", "test")
cursor = db.cursor()
sql = "INSERT INTO BOOKS(Activation Code, \
type, number,Whether ) \
VALUES (%s,%s,%s,%s)"
data = [("cl8k-k520-fg45-d4sa-sd9k",'n','10','n'),
("jhg6-58jh-gh8o-8uik-7jk8",'c','20','n'),
("x5hg-gf5h-4hj5-g4h5-fh5t",'y','999','n'),
("fg8j-h584-fd4g-fg4d-fgg4",'n','1','y'),
("4jk4-5kl4-4klk-4lji-4ghj",'e','6','n'),
]
cursor.executemany(sql,data)
db.close()
This is my first time to ask questions on this platform. I hope to get answers
enclose Activation Code as 'Activation Code'

"Invalid cursor state" error when executing a batch that includes a USE statement

I tried retrieving data from a Microsoft SQL database using pypyodbc 1.3.3 with Python 3.5 on Windows but got a pypyodbc.ProgrammingError '[24000] [Microsoft] [SQL Server Native Client 11.0] Invalid cursor state' using the following code:
import pypyodbc
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')
cursor = conn.cursor()
sql = '''USE database;
SELECT R0
FROM table;'''
cursor.execute(sql)
results = cursor.fetchone()
print(results)
The SQL works in Microsoft SQL Server Management Studio, the connection and executing worked in another script i wrote to insert into the same database and also works if i remove
results = cursor.fetchone()
So far I tried cursor.fetchone(), cursor.fetchall() and list(cursor) but all produced the same result which leads me to believe that the command itself isn't the problem.
According to this microsoft site it means that there isn't an open cursor, but I can get it's description, so from my understanding there has to be.
It's not a matter of being unable to execute a USE ... statement at all, it's just that we cannot do that as part of a multi-statement batch. So, this will not work ...
crsr.execute("""\
USE master;
SELECT TOP 2 name FROM sys.tables ORDER BY name;
""")
rows = crsr.fetchall() # error
... but this will work fine
crsr.execute("USE master")
crsr.execute("SELECT TOP 2 name FROM sys.tables ORDER BY name")
rows = crsr.fetchall()
(Tested with both pypyodbc 1.3.4 and pyodbc 4.0.21)
I had a similar issue. I was able to resolve this by removing the "USE Database" statement.
You already connected to your db here:
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')

How to avoid crashing python script when executing faulty SQL query?

I am using Python 2.7.6 and MySqldb module. I have a MySQL query that crashes sometimes. It is hard to catch the rootcause for the time being. How can I avoid crashing the python script when executing the SQL query? How can I make it fail gracefully?
The code looks like something;
cursor.execute(query)
You should throw an exception:
try:
cursor.execute(query)
except mysql.connector.Error:
"""your handling here"""
Here is a link to the MySQL Python Dev guide:
You can handle run time errors by using try except block.
At last you must use finally for cleanups like close the connection , rollback , free all the used resources etc.
Here is the example ,
import mysql.connector
try:
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
cursor.execute("SELECT * FORM employees") # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
finally:
# cleanup (close the connection, etc...)

How can I create a database using pymssql

Im trying to create a database using pymssql and im getting this error.
cur.execute("CREATE DATABASE %s;" % self.getsql('dbname'), conn)
gives
*** OperationalError: (226, 'CREATE DATABASE statement not allowed within multi-
statement transaction.DB-Lib error message 226, severity 16:\\nGeneral SQL Serve
r error: Check messages from the SQL Server\\n')
What does this mean ??
The issue was that cur.execute starts a transaction every time, but 'CREATE DATABASE' operation cannot be excuted within a transaction
http://social.msdn.microsoft.com/Forums/pl/adodotnetdataproviders/thread/594ff024-8af6-40b3-89e0-53edb3ad7245
>>> connection.autocommit(True)
>>> cursor = connection.cursor()
>>> cursor.execute("CREATE DATABASE Foo")
>>> connection.autocommit(False)
This to works. Strangely its not documented in pymssql ... hmmm

Categories