Sqlite插入查询不适用于python?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22488763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:02:14  来源:igfitidea点击:

Sqlite insert query not working with python?

pythonsqlite

提问by Saurabh

I have been trying to insert data into the database using the following code in python:

我一直在尝试使用python中的以下代码将数据插入数据库:

import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()

The code runs without any errors. But no updation to the database takes place. I tried adding the conn.commit()but it gives an error saying module not found. Please help?

代码运行没有任何错误。但是不会对数据库进行更新。我尝试添加,conn.commit()但它给出了一个错误,说找不到模块。请帮忙?

采纳答案by Martijn Pieters

You do have to commit after inserting:

您必须在插入后提交:

cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()

or use the connection as a context manager:

或使用连接作为上下文管理器

with conn:
    cursor.execute("Insert into links (link,id) values (?,?)", (a, b))

or set autocommit correctly by setting the isolation_levelkeyword parameter to the connect()method to None:

或通过将isolation_level关键字参数设置为connect()方法来正确设置自动提交None

conn = db.connect('insertlinks.db', isolation_level=None)

See Controlling Transactions.

请参阅控制事务

回答by Eduardo Cerqueira

It can be a bit late but set the autocommit = truesave my time! especially if you have a script to run some bulk action as update/insert/delete...

可能会有点晚,但设置autocommit = true节省我的时间!特别是如果你有一个脚本来运行一些批量操作update/insert/delete......

Reference:https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level

参考:https : //docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level

it is the way I usually have in my scripts:

这是我在脚本中通常采用的方式:

def get_connection():
    conn = sqlite3.connect('../db.sqlite3', isolation_level=None)
    cursor = conn.cursor()
    return conn, cursor

def get_jobs():
    conn, cursor = get_connection()

    if conn is None:
        raise DatabaseError("Could not get connection")

I hope it helps you!

我希望它能帮助你!