[英]Inserting data into multiple tables simultaneously in sqlite using python
I am trying to read in multiple files to populate multiple tables in sqlite using python. 我试图读取多个文件以使用python在sqlite中填充多个表。 I am trying to do something like this.
我正在尝试做这样的事情。
def connect_db():
return sqlite3.connect(app.config['DATABASE']) # Flask stuff
# List of tables and corresponding filenames
file_list = ['A','B','C','D']
for file in file_list:
with closing(connect_db()) as db:
cursor = db.execute('select * from ' + file)
# Get column names for the current table
names = tuple(map(lambda x: x[0], cursor.description))
filename = file + '.txt'
with open(filename, 'r') as f:
data = [row.split('\t') for row in f.readlines()]
cur.executemany('INSERT INTO' + file + ' ' + str(names) + ' VALUES ' + ???)
Now I realized that in the executemany() statement above, I need to put the syntax (?,?,?) where ? 现在,我意识到在上面的executemany()语句中,我需要将语法(?,?,?)放在哪里? is the number of columns.
是列数。 I can generate a tuple of ?
我可以生成一个元组? but then they will have quotes around them.
但是他们周围会有引号。 ('?', '?', '?').
(“?”,“?”,“?”)。 Is there a way around this?
有没有解决的办法? Thanks.
谢谢。
You can implement a query "maker", that loop over a dict or an object properties and build VALUES string with it. 您可以实现查询“制造商”,该查询遍历字典或对象属性并使用它构建VALUES字符串。 I did something like that on some project :
我在某个项目上做了类似的事情:
d = {
"id":0,
"name":"Foo",
"bar":"foobar"
}
sql = ""
for key, foo in d.iteritems():
# First, copy the current value
bar = copy.copy( foo )
# Test if number
try:
# try to increase the value of 1
bar += 1
except TypeError:
# if we can't, add double quote
foo = '"%s"' % foo
# concat with the previous sequences
sql = "%s%s=%s," % ( sql, key, foo )
# remove the latest comma ...
sql = sql[:-1]
So the value of "sql" at the end of the loop should be something like this 因此,循环末尾的“ sql”值应该是这样的
bar="foobar",id=0,name="Foo"
bar =“ foobar”,id = 0,name =“ Foo”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.