【问题标题】:insert the value from variable python msqldb从变量 python msqldb 插入值
【发布时间】:2025-12-23 18:00:16
【问题描述】:
    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","root","","project_one" )
    ahg="dfas223d";
    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    #sql = """INSERT INTO emloyee(string_one)VALUES ('Mac424234')"""
    # Execute the SQL command
    cursor.execute("insert into emloyee(string_one) values(%s)",ahg)
    # Commit your changes in the database
    db.commit()

    cursor.execute("SELECT * FROM emloyee")
    results = cursor.fetchall()
    for row in results:
    print (row)

    db.close()

这是有错误的代码 TypeError: 在字节格式化期间并非所有参数都被转换

在处理上述异常的过程中,又发生了一个异常:

Traceback(最近一次调用最后一次): 文件“E:\gatim project\module2\module4\module4.py”,第 13 行,在 cursor.execute("插入员工(string_one) 值(%s)",ahg) 执行中的文件“C:\Users\Raswanth\AppData\Local\Programs\Python\Python37-32\lib\site-packages\MySQLdb\cursors.py”,第 203 行 引发 ProgrammingError(str(m)) MySQLdb._exceptions.ProgrammingError:在字节格式化期间并非所有参数都转换

***************我找到答案了 cursor.execute("插入员工(string_one)值('%s')"%(ahg))****

【问题讨论】:

  • 参数必须是元组或列表:cursor.execute("insert into emloyee(string_one) values(%s)", [ahg])

标签: python mysql-python


【解决方案1】:

我看不到ahg 的定义位置,但正如@Klaus D. 所指出的,您需要为此提供list 的参数,而不是单个定义。

通过编写cursor.execute("insert into emloyee(string_one) values(%s)",ahg),您只插入一个值ahg,这不是values(%s) 想要做的。 values(%s) 期望遍历多个值,而不是一个,因此 ahg 需要是一个列表。

@Klaus D. 建议 cursor.execute("insert into emloyee(string_one) values(%s)", [ahg]) 将实现这一目标。

【讨论】: