python - 使用自写函数将Python列表中的值上传到MySql

标签 python mysql list

我有一个从 csv 解析的值列表。列表包含像字典一样存储的信息,我需要将列表中的值上传到MySql,尝试编写一个函数,但发生错误。错误文本: 编程错误:(1064,“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本对应的手册,了解在第 1 行 ''Nokia' VALUE 'Manufacturer'' 附近使用的正确语法”)

data = ["Manufacturer", "Nokia"]

def upload(what, where):
    import MySQLdb as db
    con = db.connect(host='localhost', user='root', passwd='somepass', db='test')
    #connecting to MySql
    cursor = con.cursor()
    insertvalue = "a"

    if what in where:
        x = where.index(what)
        x += 1
        insertitem = where[x]
    else:
        insertitem = "Not Available"

    query = "INSERT INTO phone_db %s VALUE %s"# (where to insert),(What to insert)
    args = (insertitem, what)
    #cursor.execute(query,args)
    con.commit()

最佳答案

您的 SQL 查询未指定您尝试用信息填充的列。

由于您使用的是“%s”语法,python 认为您正在尝试插入字符串而不是列名,因此它会添加“'”。

如果您确实想以这种方式指定列(至少不建议这样做),您应该这样做:

query = "INSERT INTO phone_db ({column}) VALUES (%s)".format(column = insertitem)
args = (what,)
cursor.execute(query,args)

有关 MySQL 插入语法和 Python 的更多信息可以在此处找到: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

关于python - 使用自写函数将Python列表中的值上传到MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23299422/

相关文章:

python - 使用Python创建高级频数表

mysql - 从主机连接到 mysql 容器

c++ - std::list 在首次构造时是否为空 - 即使它是类的成员?

python - Python 中的多重继承

python - sklearn log_loss 不同数量的类

php - 带问号和冒号的 MySQL 语句

javascript - 不同网站上的列表看起来不同

python - 如何并行迭代两个列表?

python - 删除 Pandas 数据框的前三行

php - 字段列表中的未知列 ""- 更新查询