Hello guys. At this time, i would share my previous experience and still about python.
I've a database table named "test" with the structure below :
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | tinyint(4) | | PRI | NULL | auto_increment |
| nama | varchar(30) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
And below is my python script :
#!/usr/bin/python
# import MySQL module
import MySQLdb
# get user input
name = raw_input("Please enter a name: ")
# connect
db = MySQLdb.connect(host="localhost", user="nobody", passwd="nobody", db="qestar", unix_socket="/tmp/mysql.sock")
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("INSERT INTO test (nama) VALUES (%s)", name)
# get ID of last inserted record
print "ID of inserted record is ", int(cursor.insert_id())
For a note, the data successfully inserted to the database, but when i wanna get the last inserted record there are an error like this below :
ID of inserted record is
Traceback (most recent call last):
File "./mysql_06.py", line 19, in ?
print "ID of inserted record is ", int(cursor.insert_id())
AttributeError: 'Cursor' object has no attribute 'insert_id'
Why i got an error like that? Is that the attribute calling name changed and not insert_id() any more ???
Ok, i would explaining to you.
To get the last inserted record on MySQL with python use cursor.lastrowid
So, the python source code would be like this :
#!/usr/bin/python
# import MySQL module
import MySQLdb
# get user input
name = raw_input("Please enter a name: ")
# connect
db = MySQLdb.connect(host="localhost", user="nobody", passwd="nobody", db="qestar", unix_socket="/tmp/mysql.sock")
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("INSERT INTO test (nama) VALUES (%s)", name)
# get ID of last inserted record
print "ID of inserted record is ", int(cursor.lastrowid)
Thank you to Mico Siahaan for helping me on solve the problem.
Thanks! This saved me too. Not documented anywhere. How did you find it?
ReplyDeleteWow, this helped me a bunch. Thanks! Where is this change documented?
ReplyDeleteGreat thx to you
ReplyDeletecursor.lastrowid does not work any more! Changed again??
ReplyDelete