python - 我的插入语句执行了两次,我不知道为什么。 sqlite3

标签 python sqlite

我有一个插入语句。

   conn = sqlite3.connect('WO1.db')


   with conn:
           cur1 = conn.cursor()
           cur1.execute("insert into workorder (Title, Link, Status) 
    values (?,?,?)", ('iijiji', 'ijjijijj', '22jhhuhij'))

   if conn:
           conn.close()

标题和链接列有独特的约束,我收到以下错误并且我的程序终止。

sqlite3.IntegrityError: UNIQUE constraint failed: 

但是 1 条新记录插入到数据库中,这正是我想要的。

然后,我创建了一个新表,其中标题和链接列没有 UNIQUE 约束。

我再次运行该程序,这次没有收到错误,但是记录被插入到表中两次,这解释了当链接和标题存在 UNIQUE 约束时出现的错误。

对于为什么此插入语句执行两次有任何逻辑解释吗?

注意这只是程序中建立连接、执行查询然后关闭连接的一个地方。除了正常配置之外,程序中没有与此数据库进行其他交互。

除此应用程序之外,我还没有使用此数据库打开任何其他 session 。

我在运行程序的 python 文件中运行此查询。

   app = Flask(__name__)

   app.config.from_object(Config)

   db = SQLAlchemy(app)

   conn = sqlite3.connect('WO1.db')


   with conn:
          cur1 = conn.cursor()
         cur1.execute("insert into workorder (Title, Link, Status) values 
  (?,?,?)", ('en24433', 'www.reddit.com', 'Not Completed'))

 if conn:
         conn.close()


 migrate = Migrate(app, db)


 @app.route('/')
 def index():
     return render_template('index.html')

 if __name__ == '__main__':
     app.run(host='localhost', port=8080, debug= True)

最佳答案

您需要重新制作数据库访问代码。

首先,通过在 conn.connect() 之后使用 with 语句在同一个数据库上连接两次。

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed.

我认为这就是您的错误的原因

在数据库中进行插入后,您需要提交更改。

This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.

请注意,close() 不会自动提交:

This closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit()first, your changes will be lost!

看看sqlite3 API docs

关于python - 我的插入语句执行了两次,我不知道为什么。 sqlite3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56058143/

相关文章:

python - 使用 __range 过滤数据

php - Perl 脚本在 crontab 中执行时无法写入数据库,尽管如果手动执行则可以写入

objective-c - 对于跨时间范围的获取等,SQLite 会比 Core Data 更受青睐吗?

javascript - Phonegap - 如何摆脱未捕获的类型错误

python - Linux - IPython 中的换行符

python - 类型错误 : unhashable type: 'list' when using built-in set function

python - OpenCV + Python : Calculate stereo reprojection error

python - 如何在 SQLAlchemy 和 Firebird 的自定义查询中将 Python 列表绑定(bind)为参数?

android - SQLite 查询未按特定顺序执行

database - 使用 sql.Open 进行 SQLite3 数据库连接