python插入mysql

标签 python mysql sql python-2.7

我正在尝试找出我的代码有什么问题。我正在尝试将数据输入 mysql,但 python 似乎不喜欢我所做的事情。

测试数据

Name = "TestRegion"
Perent= "perent"
x1 = -100.0
x2 = -150.0
z1 = 94.0
z2 = 200.0

代码

def NewRegion(Name, Perent, x1, x2, z1, z2):
  try:
    con = SQLConnect()
    cur = con.cursor()
    sql = """INSERT INTO RegionName (Name, Perent, X1, X2, Z1, Z2) VALUES (?,?,?,?,?,?)"""
    cur.execute(sql, (Name, Perent, x1, x2, z1, z2))
    con.commit()

  except mdb.Error, e:
    con.rollback()
    print "Error %d: %s" % (e.args[0],e.args[1])

  finally:           
    if con:    
        con.close()

我猜测我的问题是我如何尝试将值传递给 sql 语句。

我的错误消息是

File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py, line 159, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

最佳答案

MySQL 适配器不使用 ? 作为占位符,而是使用 %s

sql = """INSERT INTO RegionName (Name, Perent, X1, X2, Z1, Z2) VALUES (%s, %s, %s, %s, %s, %s)"""
cur.execute(sql, (Name, Perent, x1, x2, z1, z2))

关于python插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133135/

相关文章:

python - 在认知服务 API 中创建人员组时出现问题

python - 如何通过列的特定值将数据框拆分成多个部分?

sql - 寻找按类型分组的 SQL 语句

mysql - 如何同时更新Redis和MySQL中的数据?

php - 在这种情况下尝试的最佳方法(Android 应用程序)

mysql - 使用 max 时 select 返回错误的 id

sql - Oracle 12c中选择不包含某列的表

python - 使用 Python 和 RegEx 从多个 .txt 文件中提取某些数据

python - 根据另一个函数调用自动从一个函数返回

sql - SQL Server 中的嵌套表类型