免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 10442 | 回复: 7
打印 上一主题 下一主题

python插入记录后取得主键id的方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-05 18:21 |只看该作者 |倒序浏览
#!/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)

论坛徽章:
0
2 [报告]
发表于 2009-03-05 18:36 |只看该作者
??

论坛徽章:
0
3 [报告]
发表于 2009-03-06 08:53 |只看该作者
原帖由 都是虫子惹的祸 于 2009-3-5 18:21 发表
#!/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", passw ...

不知道是不是调用mysql自带的last_insert_id()函数

论坛徽章:
0
4 [报告]
发表于 2009-03-06 08:56 |只看该作者
# get ID of last inserted record
print "ID of inserted record is ", int(cursor.lastrowid)

论坛徽章:
0
5 [报告]
发表于 2009-03-06 08:59 |只看该作者
这个到底是想说明什么问题?lastrowid和主键id有什么关系?主键id是什么意思?

另外这个是不是msysql特有的,还是适用于所有数据库?

[ 本帖最后由 luffy.deng 于 2009-3-6 09:00 编辑 ]

论坛徽章:
0
6 [报告]
发表于 2009-03-06 09:04 |只看该作者
原帖由 luffy.deng 于 2009-3-6 08:59 发表
这个到底是想说明什么问题?lastrowid和主键id有什么关系?主键id是什么意思?

另外这个是不是msysql特有的,还是适用于所有数据库?

可能楼主是想帖出怎么获取last insert id把
应该是调用mysql自带函数,其他数据库可能函数不一样把。

论坛徽章:
0
7 [报告]
发表于 2009-03-06 09:06 |只看该作者
主键就是主键,行id就是行id ,主键id是什么意思?

论坛徽章:
0
8 [报告]
发表于 2009-03-06 15:33 |只看该作者
原帖由 luffy.deng 于 2009-3-6 09:06 发表
主键就是主键,行id就是行id ,主键id是什么意思?

人家帖出来也不容易,呵呵,可能只是想获取最后的insert id把。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP