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

转自: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()的结果一般情况下是一样的,最后一条记录肯定就是刚刚插入的记录。但如果是并发插入就不一样了,多线程的时候



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值