【问题标题】:Error while inserting duplicate values into DP , using ON Duplicate Key using python mysql DB使用 python mysql DB 使用 ON Duplicate Key 将重复值插入 DP 时出错
【发布时间】:2016-01-22 23:06:26
【问题描述】:

这些是 Table MyTable 中的以下条目

mysql> select * from myTable;
+------+--------+------+
| id   | name   | age  |
+------+--------+------+
|  110 | c      | 23   |
|  114 | chadns | 897  |
| 1112 | chadns | 897  |
+------+--------+------+

这是 MyTable 的架构

mysql> desc myTable;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  |     | NULL    |                |
| age   | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

执行以下代码时出现以下错误

    import MySQLdb

con_local =  MySQLdb.connect( host ="127.0.0.1",user = "root",passwd ="ctl",db ="ads")
cursor_local = con_local.cursor()

cursor_local.execute("select * from myTable")
x = cursor_local.fetchall()



for i in x:

    s = "insert into myTable values(%d,%s,%s) on duplicate key update id = id+1000"

    cursor_local.execute('''insert into myTable values(%d,%s,%s) on duplicate key update id = id+1000'''%(i[0],i[1],i[2]));
    cursor_local.execute("commit");

错误:

Traceback (most recent call last):
  File "chandu.py", line 15, in <module>
    cursor_local.execute('''insert into Chandana values(%d,%s,%s) on duplicate key update id = id+1000'''%(i[0],i[1],i[2]));
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'c' in 'field list'")

我正在尝试插入重复值,但更改了主键 id,但它不起作用,谁能告诉我解决方案

【问题讨论】:

  • execute(''' 为什么要打开 3 个单引号?
  • 您要么需要在查询中引用字符串,要么使用 Alex 的回答中准备好的查询。

标签: python mysql sql-insert mysql-python


【解决方案1】:
cursor_local.execute("insert into myTable values(%d,%s,%s) on duplicate key update id = id+1000",(int(i[0]),i[1],i[2]));

【讨论】:

  • 文件“/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py”,第 159 行,在执行 query = query % db.literal(args) TypeError: %d format : 需要一个数字,而不是 str
  • 我正在使用 %d,它不能与字符串连接,所以
  • i[0] 是一个字符串,但应该是整数
猜你喜欢
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2018-05-01
  • 2012-10-06
  • 1970-01-01
相关资源
最近更新 更多