python - 在创建表后插入数据时,python3 sqlite 表的自动递增 id 的占位符是什么?
问题描述
如果 createTable() 方法不存在,我已经创建了一个 python3 sqlite 表。之后说我想使用以下方法插入数据(insertVaribleIntoTable())。
现在对于这种方法,我不知道新行的 id 之后我将插入数据,因为它是自动递增的。
所以我没有将 id 传递给 insertVaribleIntoTable() 方法。我应该为 id 变量做什么?谁能告诉我我应该将什么作为 id 占位符传递给 insertVaribleIntoTable() 方法,因为它会在我插入数据时自动递增?谁能告诉我该怎么做?你可以看到少了一个“?” 在 insertVaribleIntoTable() 方法中的“VALUES”关键字之后。谢谢你。
def createTable(id, name, company, address, postal, country, home, business, mobile, fax, notes):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db');
cursor = sqliteConnection.cursor();
print("Connected to SQLite");
sqlite_insert_with_param = """CREATE TABLE IF NOT EXISTS 'SqliteDb_Addresser' (id INTEGER PRIMARY KEY AUTOINCREMENT, name, company, address, postal, country, home, business, mobile, fax, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""";
data_tuple = (id, name, company, address, postal, country, home, business, mobile, fax, notes);
cursor.execute(sqlite_insert_with_param, data_tuple);
sqliteConnection.commit();
print("Python Variables inserted successfully into SqliteDb_developers table");
cursor.close();
except sqlite3.Error as error:
print("Failed to insert Python variable into sqlite table", error);
finally:
if (sqliteConnection):
sqliteConnection.close();
print("The SQLite connection is closed");
def insertVaribleIntoTable(name, company, address, postal, country, home, business, mobile, fax, notes):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db');
cursor = sqliteConnection.cursor();
print("Connected to SQLite");
sqlite_insert_with_param = """INSERT INTO 'SqliteDb_Addresser'
(name, company, address, postal, country, home, business, mobile, fax, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""";
data_tuple = (name, company, address, postal, country, home, business, mobile, fax, notes);
cursor.execute(sqlite_insert_with_param, data_tuple);
sqliteConnection.commit();
print("Python Variables inserted successfully into SqliteDb_developers table");
cursor.close();
except sqlite3.Error as error:
print("Failed to insert Python variable into sqlite table", error);
finally:
if (sqliteConnection):
sqliteConnection.close();
print("The SQLite connection is closed");
解决方案
如果该列是自动递增的,则不要插入该列。它将由数据库创建。
如果要查看最后插入的 ID,可以使用 last_insert_rowid()
CREATE TABLE Person (
ID integer primary key AUTOINCREMENT,
Name varchar(20),
Age Integer
)
INSERT INTO Person (Name, Age) VALUES ('Tim', 12); -- Don't include ID
SELECT last_insert_rowid() -- 1
通过代码插入时,同样的想法也适用。
推荐阅读
- python - 无法在 python2.7 上安装 scypt
- c# - 对象 null POST 方法 Web API
- java - 使用 json-to-xml() 函数的 json 到 xml 转换会产生不合需要格式的输出
- c - 如何在C中设置变量的最大和最小限制?
- ocaml - 为什么 ocaml 中函数定义的替代方案会给出不同的结果?
- c++ - 如何在 C++ 中将整数数组向量转换为二维数组?
- java - ExpandableListview :想在每个组下添加子列表延迟加载
- mysql - Hibernate 是否验证临时表?
- drupal-8 - 以编程方式更改批量表单操作选项
- wordpress - 如何通过静态 VPS IP 访问 Wordpress