【发布时间】:2020-12-21 00:04:26
【问题描述】:
假设我在名为data.db 的数据库中有下表:
CREATE TABLE species
(
species_id int PRIMARY KEY, -- NCBI taxonomic code
abbrev character(2),
latin character varying(50),
common character varying(20)
);
如何使用 SQL 从 Python 手动将新数据添加到此数据库中?
输入函数应该如下所示:
Please define a 'species_id', that should be inserted to the database:
Please define a 'latin', that should be inserted to the database:
Please define a 'abbrev' that should be inserted to the database:
我试过的代码是这样的:
def data_add(conn, cursor, species_id, latin, abbrev):
sql = "INSERT INTO species VALUE ('{species_id}', '{latin}', '{abbrev}', NULL);"
A=input("Please define a 'species_id', that should be inserted to the database (used in task 5):")
B=input("Please define a 'latin', that should be inserted to the database (used in task 5):")
C=input("Please define a 'abbrev', that should be inserted to the database (used in task 5):")
cursor.execute(sql,[A], [B], [C])
return cursor.fetchall()
编辑 - 根据反馈更新
def data_add(conn, cursor, species_id, latin, abbrev):
species_id = input("Please define a 'species_id':")
latin = input("Please define a 'latin':")
abbrev = input("Please define a 'abbrev':")
sql = "insert into species(species_id, latin, abbrev) value (?, ?, ?);"
cursor.execute(sql, (species_id, latin, abbrev));
【问题讨论】:
-
请用您正在运行的数据库标记您的问题:mysql、oracle、postgres...?
-
更新了该信息
-
Sqlite和mysql是两种不同的数据库产品,不同的sql语法。删除了冲突的产品标签。请添加您实际使用的那个!
-
我用的是sqlite3,但是没有use标签。不过sqlite标签是存在的,所以我加了。
-
你有什么想法@Shadow
标签: python sql sqlite sql-insert