执行INSERT INTO语句
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
我想要得到主键。
我的表格有2列:
id primary, auto increment
height this is the other column.
我怎么得到“id”,在我刚刚插入这个?
执行INSERT INTO语句
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
我想要得到主键。
我的表格有2列:
id primary, auto increment
height this is the other column.
我怎么得到“id”,在我刚刚插入这个?
当前回答
此外,游标。lastrowid (MySQLdb支持的dbapi/PEP249扩展):
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)
游标。lastrowid比connection.insert_id()更便宜,而且比另一个到MySQL的往返要便宜得多。
其他回答
SELECT @@IDENTITY AS 'Identity';
or
SELECT last_insert_id();
使用游标。lastrowid获取游标对象上插入的最后一行ID,或者connection.insert_id()获取该连接上最后插入的ID。
这可能只是Python中PyMySql的一个要求,但我发现我必须准确地命名我想要ID的表:
In:
cnx = pymysql.connect(host='host',
database='db',
user='user',
password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22 ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()
batch_id
: 5 …或者正确的Batch_ID值
此外,游标。lastrowid (MySQLdb支持的dbapi/PEP249扩展):
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)
游标。lastrowid比connection.insert_id()更便宜,而且比另一个到MySQL的往返要便宜得多。
Python DBAPI规范还为光标对象定义了'lastrowid'属性,因此…
id = cursor.lastrowid
...应该也能工作,而且显然是基于每个连接的。