Sqlite3与python插入相同的行

时间:2014-07-07 17:22:03

标签: python sqlite

我遇到了在sqlite3中插入不同行的python脚本的问题。但我希望它插入同一行。我很擅长使用脚本将信息插入到数据库中,因此我的知识有限。

我的数据库自动增量中的ID。有没有办法更新插入信息的上一行? 我希望一切都在数据库中的一行。感谢任何帮助,谢谢。

Sqlite表:

create table ansible_packagelist (id integer PRIMARY KEY, date datetime default current_timestamp, host text, package_name text, installed_version text NULL, upgradeable_version text NULL, required_version text NULL);

下面是我的python代码。

import apt
import sys, getopt
import subprocess
import sqlite3

con = sqlite3.connect("ansible.db")

def aptpkg(package_name):
    cache = apt.Cache()
    pkg = cache[package_name]
    host = subprocess.Popen('hostname', stdout=subprocess.PIPE, universal_newlines=True).stdout.read().strip()
    if pkg.is_installed:
        print host
        print 'Current ' + package_name + ' installed:', pkg.installed.version
        con.execute("insert into ansible_packagelist (date, host, package_name, installed_version) values (current_timestamp,?,?,?)", (host, package_name, pkg.installed.version,))
    else:
        print host, package_name + ' is not installed on this system.\n'
    if pkg.is_upgradable:
        print 'Upgradeable version of ' + package_name + ' :', pkg.candidate.version
        con.execute("insert into ansible_packagelist (upgradeable_version) values (?)", (pkg.candidate.version,))
    con.commit()

def aptver(package_version):
    cache1 = apt.Cache()
    pkg1 = cache1[packname]
    con.execute("insert into ansible_packagelist (required_package) values (?)", (package_version,))
    if package_version >= pkg1.installed.version:
        print 'The Package needs to be upgraded, ' + package_version + ' is the version needed'
    elif package_version == pkg1.installed.version:
        print 'The package is at the correct version'
    elif package_version <= pkg1.installed.version:
        print 'The package is at a greater version than requested'
    else:
        print 'The package is at the correct version'
    con.commit()

1 个答案:

答案 0 :(得分:2)

在SQL中,Insert将始终创建一个新行。

要修改现有行,您需要使用Update语句。要做到这一点,虽然你需要一个唯一的键匹配。在这种情况下,您可以使用包名称逃脱。但通常你想获取ID(你设置为自动增量)并在你的代码中引用它。

您的可升级更新语句应如下所示

 con.execute("Update ansible_packagelist Set upgradeable_version = ? Where package_name = ?", (pkg.candidate.version, package_name))