Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python sqlite3插入命令_Python_Insert_Sqlite - Fatal编程技术网

python sqlite3插入命令

python sqlite3插入命令,python,insert,sqlite,Python,Insert,Sqlite,知道我做错了什么吗 我正在创建一个名为General的表: conn = sqlite3.connect(self.dbLocation) c = conn.cursor() sql = "create table if not exists General (id integer NOT NULL,current char[20] NOT NULL,PRIMARY KEY (id))" c.execute(sql) c.close()

知道我做错了什么吗

我正在创建一个名为General的表:

    conn = sqlite3.connect(self.dbLocation)
    c = conn.cursor()        
    sql = "create table if not exists General (id integer NOT NULL,current char[20] NOT NULL,PRIMARY KEY (id))"
    c.execute(sql)
    c.close()
    conn.close()
然后我使用max(id)查看表是否为空。如果是,我将创建一个名为Current1的表,并插入一行(id,“Current1”)。id为自动递增整数:

    self.currentDB = "Current1"
    self.currentDBID = "1"
    #create the table
    sql = "create table %s (id integer NOT NULL,key char[90] NOT NULL,value float NOT NULL,PRIMARY KEY (id))" % (str(self.currentDB))
    c.execute(sql)
    c.close()
    conn.close()
    conn = sqlite3.connect(self.dbLocation)
    c = conn.cursor()
    sql = "insert into General(current) values('%s')" % (str(self.currentDB))
    print "sql = %s" % (str(sql)) ---> *sql = insert into General(current) values('Current1')*
    c.execute(sql)
    print "executed insert Current"
    c.execute ("select max(id) from General")
    temp = c.next()[0]
    print "temp = %s" % (str(temp)) ---> *temp = 1*
    c.close()
    conn.close()

问题是,如果打开数据库,在常规表中找不到任何行。正在创建Current1表,但在General中的insert语句似乎没有任何作用。我做错了什么?谢谢。

您必须在关闭连接之前提交更改:

conn.commit()

检查文档中的示例:

,或者您可以将连接用作上下文管理器:

连接对象可用作自动提交或回滚事务的上下文管理器。如果发生异常,事务将回滚;否则,事务将被提交

例如:

import sqlite3
conn = sqlite3.connect('current')
with conn:
    conn.execute("create table if not exists General (id integer NOT NULL,current char[20] NOT NULL,PRIMARY KEY (id))")
    conn.execute("insert into General(current) values('{0}')".format("some data"))

with conn:
    q = conn.execute("select max(id) from General")
q.fetchone()[0]

您需要使用提交数据库中的更改

conn.commit()

这将在磁盘上写入您在数据库中所做的更改。如果不关闭数据库,则会丢失修改(插入/更新/删除)

在我刷新此页面并找到您的答案之前,您在另一个页面上找到了答案。你是对的,我也尝试过使用变量c提交,但没有成功…它必须在conn上。非常感谢:)将标记你的答案为正确答案,因为你的答案是第一个,即使@Maxime Lorant也是正确的!