将包含多个项目的列表插入到mysql数据库中

时间:2013-06-06 11:33:29

标签: python mysql database list

我有一个这样的清单:

list = [('name1', 'id1', 'created_at1'),('name2', 'id2', 'created_at2'),('name3', 'id3', 'created_at3')]

我想用MySQLdb把它放到一个Mysql数据库中,它最终看起来像这样:

Name   ID    Created_at
name1  id1   created_at1
name2  id2   created_at2
name3  id3   created_at3

我尝试过类似的事情:

for s in list:
   var_string = ', '.join('?' * len(s))
   query_string = 'INSERT INTO TweetsTest VALUES (%s);' % s
   cursor.execute(query_string, varlist)

但它不起作用。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

这应该这样做:

sql = ("INSERT INTO TweetsTest "
       "(Name, ID, Created_at) VALUES ")

for item in list:
    sqlRow = "('%s', '{1}', '{2}'), ".format(item[1], item[2]) % item[0]
    sql += sqlRow

sql = sql[:-2] + ";"
cursors.execute(sql)

以上所有意味着这三个字段都是基于字符串的,因此for循环中的引号。对于所有数字字段 - 删除引号。