Python MySQLdb cursor.lastrowid - python

I'm having problems returning auto-incremented ID columns from a MySQL database using MySQLdb python library.
I have something like:
sql = """INSERT INTO %s (%s) VALUES (\"%s\")""" %(tbl, colsf, valsf)
try:
cursor.execute(sql)
id = cursor.lastrowid
db.close()
except:
print "Failed to add to MySQL database: \n%s" %sql
print sys.exc_info()
db.close()
exit()
However the lastrowid command seems to be returning incorrect values. For instance, I've tried printing out various id columns from the MySQL command line which shows them to be empty, but the lastrowid value keeps increasing by 1 every time the python script is run. Any ideas?

Turned out that the values weren't being committed to the MySQL database properly, adding "db.commit()" command seems to solve the problem.
sql = """INSERT INTO %s (%s) VALUES (\"%s\")""" %(tbl, colsf, valsf)
try:
cursor.execute(sql)
id = cursor.lastrowid
cursor.close()
db.commit()
db.close()
except:
print "Failed to add to MySQL database: \n%s" %sql
print sys.exc_info()
db.close()
exit()

Related

Skip if value exists in database mysql database - pymysql

Is there an exception in my pymysql insert statement below that I can use here to pass on looping if the value already exists?
My code looks like:
try:
with db.cursor() as cursor:
sqltld = "INSERT INTO `table`(`colname`) VALUES (%s)"
cursor.execute(sqltld, (self.url))
db.commit()
except:
print("error INSERTing url")
db.rollback()
Mysql is already enforcing unique on the column colname
Thanks

python MySQLdb won't INSERT

I'm using python-mysql, attacked below is the code snippet I'm using to insert into a database table. For some reasons, the code is not populating any rows in the database. There are no exceptions raised and the SELECT queries work fine. On copying the code inside execute and running in phpmyadmin, the database is populated fine.
import MySQLdb as mdb
try:
con = mdb.connect(host='localhost', user='', passwd='', db='indoor')
cur = con.cursor()
cur.execute("INSERT INTO locationdata VALUES('1','1','1','1','1','1')")
numrows = cur.execute("SELECT * FROM locationdata")
print str(numrows) + " : total Rows"
print cur.fetchone()
if con.open:
print "Hello DB"
except mdb.Error, e:
Print "Error " + e. args [0]
Any ideas what am I missing?

Can't execute an INSERT statement in a Python script via MySQLdb

I'm trying to execute a basic INSERT statement on a MySQL table from a Python script using MySQLdb. My table looks like this:
CREATE TABLE `testtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testfield` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
Running this query from the MySQL command line works fine:
INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue');
But when I try to execute the query from a Python script, no rows get inserted. Here's my code:
conn = MySQLdb.connect(host=db_host, port=db_port, user=db_user, passwd=db_password, db=db_database)
cursor = conn.cursor ()
cursor.execute ("INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue')")
print "Number of rows inserted: %d" % cursor.rowcount
cursor.close()
conn.close()
Oddly, this will print "Number of rows inserted: 1." I can also confirm that this query increments the ID field, because when I add another row via the command line, the value of its ID is the same as if the Python script had successfully inserted its rows. However, running a SELECT query returns none of the rows from the script.
Any idea what's going wrong?
You either need to set conn.autocommit(), or you need to do conn.commit() - see the FAQ
you need to commit:
conn.commit()
http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away

why cx_Oracle and sqlplus give different results for the same select query

By using Python and cx_Oracle, I am trying to insert rows to a table.
con = cx_Oracle.connect(ORACLE_USER+'/'+PASS+'#'+TNS)
cursor = con.cursor()
...
try:
cursor.executemany("INSERT INTO table(ID,NAME) VALUES(...)"
except cx_Oracle,exc:
error ,=exc.args
print error.code
print error.message
cursor.close()
con.close()
After insert all the rows from an input file, by using select query in cx_Oracle, I can see the inserted rows. However, sqlplus gives no results when I enter "select * from table;"
Is there something that I missed about cx_Oracle or is there a buffer in oracle client that shows the old results with sqlplus when it is connected to a remote db?
Have you committed your insert?
con.commit() #after inserts
or
con.autocommit = true #before inserts
I had an inverted problem: I added rows using sqlquery and after 2 hours of suffering read this post and guess, that I should close my session. I closed the console and managed to get my data!

multiple sql in python

i am trying to send two SQL ( select and update) in one python file. but getting still error
cursor = cnx.cursor()
query = "select id, mail from `candidats`; UPDATE candidats SET statusmail=1 "
results = cursor.execute(query, multi=True)
for cur in results:
print('cursor:', cur)
print('result:', cur.fetchall())
cursor.close()
cnx.close()
getting this error:
mysql.connector.errors.InterfaceError: No result set to fetch from

Categories