python - Sqlite3与python插入同一行

标签 python sqlite

我在将 python 脚本插入 sqlite3 中的不同行时遇到问题。但我希望它插入到同一行。我对使用脚本将信息插入数据库还很陌生,因此我对此的了解有限。

我的数据库自动增量中的 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()

最佳答案

在 SQL 插入中总是会创建一个新行。

要修改现有行,您需要使用 Update 语句。为此,您需要一个唯一的 key 来匹配。在这种情况下,您可能可以不用使用包名称。但通常您希望获取 ID(设置为自动增量)并在代码中引用它。

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

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

关于python - Sqlite3与python插入同一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616260/

相关文章:

python - 为什么 Python 的 Numpy zeros 和空函数之间的速度差异对于更大的数组大小消失了?

python - 比较 pandas 映射和合并

python-3.x - 在sqlite3和python Tkinter中插入电子邮件字符串时出错

python - Django 模型没有将日期字段转换为 datetime.date?

Android SqlCipher 性能问题

python - 使用 join() 的方法的空间复杂度

python - 任何快速的 Python GUI 来显示来自相机的实时图像

数据科学项目的 Python 文件命名约定

c++ - Qt 添加表格小部件项目时出现问题

c# - Xamarin ListView 显示 SQLite 数据库中的项目 C# Android