Py学习  »  Python

Python只在SQLite数据库中插入一行

Carlos • 4 年前 • 595 次点击  

为什么我的代码只插入一行?

thewholeenchilada = ("SELECT SUBSTR(email, (SELECT INSTR(email,'@'))) AS org, SUM(count) as count FROM Em GROUP BY org ORDER BY count DESC")

for salida in cur.execute(thewholeenchilada):
    cur.execute('''INSERT INTO Counts (org, count)
                VALUES (?, ?)''', (salida[0],row[1]))

    print((str(salida[0]), salida[1]))
    conn.commit()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50907
 
595 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Parfait
Reply   •   1 楼
Parfait    5 年前

避免循环,运行一个 INSERT INTO ... SELECT 查询。现在,您在循环内外重用同一个游标,这会导致处理问题。使用两个不同的游标或有效地组合并让数据库引擎运行操作查询:

sql = '''INSERT INTO Counts (org, [count])
         SELECT SUBSTR(email, INSTR(email, '@')+1) AS org, 
                SUM(count) as [count]
         FROM Em 
         GROUP BY org 
         ORDER BY count DESC
      '''

cur.execute(sql)
conn.commit()