首页 > 解决方案 > 面临 Python 到 MYSQL 插入的问题

问题描述

我尝试使用几种方法将数据插入 mysql 数据库,但全部出错:在第一种方法中:

sql = ('''Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email)        
 VALUES (%d,$s,$s,$s,$s,$d,$s)''', (eid, name, gen, dob, add, mob, email))

mycursor.execute(sql)
mycursor.commit()

这种方法的错误:

'tuple' object has no attribute 'encode'

方法二:

sql = "Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email)  VALUES(?,?,?,?,?,?,?,)"
val =  (eid, name, gen, dob, add, mob, email)
mycursor.execute(sql, val)
mycursor.commit()

这种方法的错误

    "Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

我已经解决了很多问题,但没有运气。任何人都可以帮忙,因为我在哪里错了,或者还有什么可以将数据从 python 插入 mysql 的好选择。

标签: pythonmysqlinsert

解决方案


我不知道你的错误在哪里,但我用这段代码测试过,它可以工作。

        insert_tuple = (eid, name, gen, dob, add, mob, email)
        sql = """INSERT INTO lgemployees (`EmpID `, 
        `Name`,`Gender`, `DOB`, `Address`, `PhoneNumber`, `Email`)
        VALUES (%s,%s,%s,%s,%s,%s,%s)"""
        mycursor = mySQLconnection.cursor()
        mycursor.execute(sql, insert_tuple)
        mySQLconnection.commit()
        mycursor.close()

您的代码会抛出此问题,因为其中一个参数为空或格式无法读取。

  "Not all parameters were used in the SQL statement")
    mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

推荐阅读