在python中使用MySQLdb在mysql插入后,如何安全有效地获取行ID? [英] How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?

查看:79
本文介绍了在python中使用MySQLdb在mysql插入后,如何安全有效地获取行ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mysql中有一个简单的表,其中包含以下字段:

I have a simple table in mysql with the following fields:

  • id-主键,整数,自动增量
  • 名称-varchar(50)
  • 说明-varchar(256)

使用MySQLdb(一个python模块),我想在表中插入名称和描述,并获取ID.

Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.

使用伪代码:

db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"

db.execute(queryString);
newID = ???

推荐答案

我认为可能是

newID = db.insert_id()


由原始海报编辑

结果是,在我正在使用的MySQLdb版本(1.2.2)中 您将执行以下操作:

Turns out, in the version of MySQLdb that I am using (1.2.2) You would do the following:

conn = MySQLdb(host...)

c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid

我将其作为正确的答案,因为它使我指向了正确的方向.

I am leaving this as the correct answer, since it got me pointed in the right direction.

这篇关于在python中使用MySQLdb在mysql插入后,如何安全有效地获取行ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆