创建一个简单的数据库,并具有带id的行,以便以后可以选择行值:
conn = sqlite3.connect("APIlan.db")
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS ENERGYLOG (id INTEGER PRIMARY KEY AUTOINCREMENT, totalenergy REAL)''')
c.execute("INSERT INTO ENERGYLOG VALUES (?);", (total_energy,))
conn.commit()
conn.close()
错误sqlite3.OperationalError: table ENERGYLOG has 2 columns but 1 values were supplied
第二次尝试:
conn = sqlite3.connect("APIlan.db")
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS ENERGYLOG (id INTEGER PRIMARY KEY AUTOINCREMENT, totalenergy REAL)''')
c.execute("INSERT INTO ENERGYLOG VALUES (?,?);", (NULL,total_energy,))
conn.commit()
conn.close()
错误NameError: name 'NULL' is not defined
如果不提供id的值,如何将其放入表中?谢谢
我有两个解决方案。
1.你的第一次尝试,如果你只想插入你选择的列,你可以遵循以下语法:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)] VALUES (value1, value2, value3,...valueN);
所以,你可以这样写:
c.execute("INSERT INTO ENERGYLOG (totalenergy) VALUES (?);", (total_energy,))
2.第二次尝试时,如果要插入所有列,可以将"NULL"替换为"None":
c.execute("INSERT INTO ENERGYLOG VALUES (?, ?);", (None, total_energy))
因为python不知道"NULL"。
在SQL中,我们使用"NULL",在python中,我们则使用"None"。
希望它能帮助你!
您应该明确列出要插入的列:
c.execute("INSERT INTO ENERGYLOG (totalenergy) VALUES (?);", (total_energy,))
至于参数化NULL
,您应该指定None
作为参数值:
c.execute("INSERT INTO ENERGYLOG VALUES (?, ?);", (None, total_energy))
或者,使用NULL
和单个参数:
c.execute("INSERT INTO ENERGYLOG VALUES (NULL, ?);", (total_energy,))