Python MySQLdb没有插入所有记录

时间:2017-08-22 18:05:42

标签: python mysql sql

我坚持使用Python脚本。这个脚本应该填充一个MySQL表,从select语句中获取值。

问题是当我从select语句中获取值时,insert into语句不能正常工作而不会插入所有记录。我在MySQL WorkBench中检查了相同的select语句,并返回了我想要放在目标表中的正确记录数。 select语句是这样的,并且预期的行数超过100.000(是一个大数据库):

SELECT MAX(c1),MAX(c2),MAX(c3),MAX(c4),c5,c6,MAX(c7)
FROM Table1 as t1
INNER JOIN Table2 as t2 ON t1.Id = t2.Id
INNER JOIN Table3 as t3 ON t1.Id = t3.Id
WHERE c4 NOT LIKE '%A%'
GROUP BY t1.c1;

此select语句应返回不包含' A'字符。

这是我的Python代码:

import MySQLdb

db = MySQLdb.connect(host,user,pass,dbName)
cursor = db.cursor()
cursor.execute("SELECT MAX(c1),MAX(c2),MAX(c3),MAX(c4),c5,c6,MAX(c7)
     FROM Table1 as t1
     INNER JOIN Table2 as t2 ON t1.Id = t2.Id
     INNER JOIN Table3 as t3 ON t1.Id = t3.Id
     WHERE c4 NOT LIKE '%A%'
     GROUP BY t1.c1")

results = cursor.fetchall()

for row in results:
    cursor.execute("INSERT INTO DestinationTable(col1,col2,col3,col4,col5,col6)VALUES('%s','%s','%s','%s','%s','%s')"
         %(str(row[1]),str(row[2]),str(row[3]),str(row[4]),str(row[5]),str(row[6]))
   db.commit()

我认为问题出在Insert into语句中,但我不确定。

1 个答案:

答案 0 :(得分:2)

只需运行一个INSERT INTO ... SELECT而不是...VALUES,它不需要循环或SQL字符串插值(无论如何都应该parameterized)。

以下MAX(c1)已从SELECT语句中删除,因为您在尝试查询时跳过了它:

sql = "INSERT INTO DestinationTable(col1, col2, col3, col4, col5, col6)
       SELECT MAX(c2), MAX(c3), MAX(c4), c5, c6, MAX(c7)
       FROM Table1 as t1
       INNER JOIN Table2 as t2 ON t1.Id = t2.Id
       INNER JOIN Table3 as t3 ON t1.Id = t3.Id
       WHERE c4 NOT LIKE '%A%'
       GROUP BY t1.c1"

cursor.execute(sql)
db.commit()