我试图在多个文件中读取使用python在sqlite中填充多个表。我正在尝试这样做。
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 ' + ???)
现在我意识到在上面的executemany()语句中,我需要把语法(?,?,?)放在哪里?是列数。我可以生成一个元组?但他们会在他们身边引用。 ('?','?','?')。有没有解决的办法?感谢。
答案 0 :(得分:0)
您可以实现查询“maker”,循环遍历dict或对象属性,并使用它构建VALUES字符串。 我在某个项目上做了类似的事情:
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]
所以循环结束时“sql”的值应该是这样的
巴= “foobar的”,ID = 0,名字= “foo” 的