python插入记录后取得主键id的方法(cursor.lastrowid和conn.insert_id())

来源:互联网 发布:hbuilder手机版软件 编辑:程序博客网 时间:2024/05/17 01:57

转自:http://hi.bccn.net/space-2-do-blog-id-16315.html

 

[python] view plain copy
  1. #!/usr/bin/python  
  2. # import MySQL module  
  3. import MySQLdb  
  4. # get user input  
  5. name = raw_input("Please enter a name: ")  
  6. # connect  
  7. conn = MySQLdb.connect(host="localhost", user="nobody", passwd="nobody", conn="qestar", unix_socket="/tmp/mysql.sock")  
  8. # create a cursor  
  9. cursor = conn.cursor()  
  10. # execute SQL statement  
  11. cursor.execute("INSERT INTO test (nama) VALUES (%s)", name)  
  12. # get ID of last inserted record  
  13. print "ID of last record is ", int(cursor.lastrowid) #最后插入行的主键ID  
  14. print "ID of inserted record is ", int(conn.insert_id()) #最新插入行的主键ID,conn.insert_id()一定要在conn.commit()之前,否则会返回0  
  15. conn.commit()  
 

 

cursor.lastrowid跟conn.insert_id()的结果一般情况下是一样的,最后一条记录肯定就是刚刚插入的记录。但如果是并发插入就不一样了,多线程的时候



阅读全文
0 0
原创粉丝点击