如果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");发布于 2020-08-01 01:41:25
如果列是自动增量,则不插入该列.它将由数据库创建。
如果希望看到最后插入的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同样的想法也适用于通过代码插入。
https://stackoverflow.com/questions/63200097
复制相似问题