【问题标题】:mysql insert table by pythonmysql通过python插入表
【发布时间】:2018-07-24 07:36:57
【问题描述】:

我只想将表列表插入到mysql数据库表中。代码如下:

import mysql.connector 
# Open database connection
a = [('apq3'), ('aquaporin')]
b = ["skin"]
c = ["down-regulated", "down regulation", "down regulate"]

def input_mysql(a1, b1, c1):
    db = mysql.connector.connect(user='root', password='xxxx',
                              host='localhost',
                              database='crawling')
    #sql = 'INSERT INTO crawling_result(search_content, content) VALUES(%s)' 
    sql_target_a = 'INSERT INTO a (term) VALUES(%s)'
    sql_target_b = 'INSERT INTO b (term) VALUES(%s)'
    sql_target_c = 'INSERT INTO c (term) VALUES(%s)'
    cursor=db.cursor()
    cursor.execute(sql_target_a, a1)
    cursor.execute(sql_target_b, b1)
    cursor.execute(sql_target_c, c1)
    db.commit()
    db.close()

a_content = a
b_content = b
c_content = c
input_mysql (a_content, b_content, c_content)

运行后一直提示“mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement”。有人可以帮我吗?

【问题讨论】:

    标签: python mysql sql-insert


    【解决方案1】:

    您的某些列表 - ac - 有多个值,但您在语句 (%s) 中只使用了一个值。这被认为是一个错误,因为不清楚额外参数是否是故意的。

    如果您打算在源数组中的每个元素插入一行,请使用executemany 并传入一系列参数:

    a = [('apq3',), ('aquaporin',)]
    b = [('skin',)]
    c = [('down-regulated',), ('down regulation',) ('down regulate',)]
    
    [...]
    
    # Insert two rows (one for each parameter list in `a`)
    cursor.executemany('INSERT INTO a (term) VALUES(%s)', a)
    

    【讨论】:

    • 谢谢。那么如何将具有多个值的列表插入到 mysql.table 中呢?我只想插入“术语”列。
    • @Thomas.Q 看看executemany 或许?不过,您必须将输入重新格式化为元组列表
    • 是的。只需将其更改为 cursor.executemany(sql_target_a, [(x,) for x in a1])。它有效!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2017-08-16
    相关资源
    最近更新 更多