简体   繁体   English

python:更新现有的sqlite数据库

[英]python: update an existing sqlite db

Have a python script that creates a sqlite database: 有一个创建sqlite数据库的python脚本:

import sqlite3

con = sqlite3.connect('some.db',detect_types=sqlite3.PARSE_DECLTYPES)
with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE Title(ID INT, ...)")

and then later populates the db with content from a list: 然后,使用列表中的内容填充数据库:

    <ID> = <whatever>
    <var1> = <you get the point>

    altogether = (ID, var1...)
    cur.execute("INSERT INTO Title VALUES(?,?,...)", altogether)
    con.commit()

I now want to write a modified version of this script that takes an existing some.db and updates it, but only does so if the ID doesn't already exist in the database. 现在,我想编写此脚本的修改版本,该版本采用现有的some.db并更新它,但是只有在数据库中不存在该ID时才这样做。

How do I: 我如何:

  1. open some.db for read/write to update values only 打开some.db进行读/写以仅更新值

  2. query the db to make sure that the ID of the item that I'm currently iterating through does not already exist in the db? 查询数据库以确保我当前正在迭代的itemID在数据库中不存在? The way that I'm currently populating variables is by making API calls to an external service that I'd like to be able to skip if the entry is already in my db. 我当前填充变量的方式是通过对外部服务进行API调用,如果该条目已经存在于数据库中,那么我希望能够跳过该外部服务。

  1. Same way you already did. 您已经做过了。

  2. Don't. 别。 Make the column UNIQUE and handle the exception on INSERT . 使列成为UNIQUE并处理INSERT上的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM