[英]MySQL + Python:Using auto increment primary key
我的數據庫中有一個表,如下所示,我正在嘗試將數據插入其中;
CREATE TABLE student (
student_id int AUTO_INCREMENT,
first_name varchar (20) NOT NULL,
last_name varchar (20) NOT NULL,
year_began int NOT NULL,
PRIMARY KEY (student_id)
使用 python 需要在下面的代碼中添加什么才能使自動遞增主鍵對每個新條目起作用?
cursor = mydb.cursor()
cursor.execute ("INSERT INTO student (first_name, last_name, year_began) VALUES ('{}','{}','{}');".format(first_name, last_name, year_began))
mydb.commit()
cursor.close()
抱歉,如果這看起來很簡單……新手。 任何幫助將非常感激。
我不知道 python。 但是,你可以試試這個。
print "ID of last record is ", int(cursor.lastrowid)
print "ID of inserted record is ", int(conn.insert_id())
代碼必須在 mydb.commit() 前面
https://www.w3schools.com/python/showpython.asp?filename=demo_mysql_primary_key
這可能會有所幫助..您需要添加主鍵屬性
在創建表時或嘗試在...之后執行
數據是否已經在數據庫中,並且您想將鍵添加到現有數據或最終將添加的數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.