gpt4 book ai didi

Python 将多列写入sqlite

转载 作者:行者123 更新时间:2023-12-01 05:55:00 25 4
gpt4 key购买 nike

我正在开发一个小项目,我创建了一个辅助函数,它将把一串逗号分隔值写入数据库,就像它们是值一样。我意识到这样做会产生影响,但这很小,我需要继续下去,直到我能做得更好

def db_insert(table,data):
"""
insert data into a table, the data should be a tuple
matching the number of columns with null for any columns that
have no value. False is returned on any error, error is logged to
database log file."""

if os.path.exists(database_name):
con = lite.connect(database_name)

else:
error = "Database file does not exist."
to_log(error)
return False

if con:
try:
cur = con.cursor()
data = str(data)
cur.execute('insert into %s values(%s)') % (table, data)
con.commit()
con.close()

except Exception, e:
pre_error = "Database insert raised and error;\n"
thrown_error = pre_error + str(e)
to_log(thrown_error)

finally:
con.close()


else:
error = "No connection to database"
to_log(error)
return False

database_name 等...在脚本的其他地方定义。

除非有任何其他明显的错误;我需要能够做的(通过这种方法或其他方法,如果有建议的话)是允许某人创建一个列表,其中每个值代表一个列值。因为我不知道有多少列被填充。

所以有人按如下方式使用它:
数据 = ["null", "foo","bar"]
db_insert("foo_table", 数据)

这将该数据插入到表名 foo_table 中。用户需要知道表中有多少列,并提供正确数量的元素来满足该要求。我意识到使用 sqlite 参数更好,但有两个问题。首先,您不能使用参数仅指定表中的值。其次,您需要知道您提供了多少个值。你必须做;

cur.execute('插入表值(?,?,?), val1,val2,val3)

您需要能够指定三个?。我正在尝试编写一个通用函数,该函数允许我获取任意数量的值并将它们插入到任意表名中。现在,它工作得相对正常,直到我尝试传入“null”作为值。其中一列是主键并且具有自动增量。所以传入 null 将允许它自动递增。还存在需要空值的其他情况。问题是 python 不断将我的 null 用单引号括起来,sqlite 提示数据类型不匹配,因为主键是整数字段。如果我尝试将 None 作为 python null 等效项传递,则会发生同样的事情。所以有两个问题。

如何插入任意数量的列。
如何传递 null。

感谢您对这个问题和过去的问题提供的所有帮助。

抱歉,这看起来与此重复 Using Python quick insert many columns into Sqlite\Mysql

很抱歉,直到我写完这篇文章后才找到它。

产生以下有效结果;

def db_insert(table,data):
"""
insert data into a table, the data should be a tuple
matching the number of columns with null for any columns that
have no value. False is returned on any error, error is logged to
database log file."""

if os.path.exists(database_name):
con = lite.connect(database_name)

else:
error = "Database file does not exist."
to_log(error)
return False

if con:
try:
tuple_len = len(data)
holders = ','.join('?' * tuple_len)

sql_query = 'insert into %s values({0})'.format(holders) % table
cur = con.cursor()
#data = str(data)
#cur.execute('insert into readings values(%s)') % table
cur.execute(sql_query, data)
con.commit()
con.close()

except Exception, e:
pre_error = "Database insert raised and error;\n"
thrown_error = pre_error + str(e)
to_log(thrown_error)

finally:
con.close()


else:
error = "No connection to database"
to_log(error)
return False

最佳答案

第二个问题是“为我工作”。当我将 None 作为值传递时,它将正确地将该值与数据库来回转换。

import sqlite3
conn = sqlite3.connect("test.sqlite")

data = ("a", None)
conn.execute('INSERT INTO "foo" VALUES(' + ','.join("?" * len(data)) + ')', data)

list(conn.execute("SELECT * FROM foo")) # -> [("a", None)]

关于Python 将多列写入sqlite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13017036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com