新 Table 包含字典中的字段?
New Table with Fields from Dictionary?
如何在 sqlite3 中创建一个 table 并将字典项作为字段?
我不能简单地手动定义每个字段,因为我有很多不同大小的词典。有办法实现吗?
以下是我到目前为止得出的结论:
import sqlite3
DICT = { 'field 1': 'TEXT',
'field 2': 'TEXT',
'field 3': 'INT',
'field 4': 'TEXT'
'field x': '???'
}
def create_table(DICT):
with sqlite3.connect("data.db") as connection:
cursor = connection.cursor()
# should instead iterate over the dictionary and create a field for each entry
cursor.execute("""CREATE TABLE table_name
(dict_key_x, DICT_VALUE_X)""")
connection.close()
欢迎任何想法。谢谢! :)
您当然可以通过构建字符串列表并使用 ',\n' .join
来做到这一点
DICT = {'field 1': 'TEXT',
'field 2': 'TEXT',
'field 3': 'INT',
'field 4': 'TEXT'
'field x': '???'}
columns = "(" + ",\n".join(["{} {}".format(k,v) for k,v in DICT.items()]) + ")"
# looks like:
# # """(field 1 TEXT,
# # field 2 TEXT,
# # field 3 INT,
# # field 4 TEXT,
# # field x ???)"""
with sqlite.connect('data.db') as connection:
cursor = connections.cursor()
cursor.execute("CREATE TABLE table_name\n" + columns)
# you don't have to close the connection if you're using a with statement
如何在 sqlite3 中创建一个 table 并将字典项作为字段?
我不能简单地手动定义每个字段,因为我有很多不同大小的词典。有办法实现吗?
以下是我到目前为止得出的结论:
import sqlite3
DICT = { 'field 1': 'TEXT',
'field 2': 'TEXT',
'field 3': 'INT',
'field 4': 'TEXT'
'field x': '???'
}
def create_table(DICT):
with sqlite3.connect("data.db") as connection:
cursor = connection.cursor()
# should instead iterate over the dictionary and create a field for each entry
cursor.execute("""CREATE TABLE table_name
(dict_key_x, DICT_VALUE_X)""")
connection.close()
欢迎任何想法。谢谢! :)
您当然可以通过构建字符串列表并使用 ',\n' .join
DICT = {'field 1': 'TEXT',
'field 2': 'TEXT',
'field 3': 'INT',
'field 4': 'TEXT'
'field x': '???'}
columns = "(" + ",\n".join(["{} {}".format(k,v) for k,v in DICT.items()]) + ")"
# looks like:
# # """(field 1 TEXT,
# # field 2 TEXT,
# # field 3 INT,
# # field 4 TEXT,
# # field x ???)"""
with sqlite.connect('data.db') as connection:
cursor = connections.cursor()
cursor.execute("CREATE TABLE table_name\n" + columns)
# you don't have to close the connection if you're using a with statement