使用python mysql DB使用ON Duplicate Key将重复值插入DP时出错

时间:2015-10-23 12:03:55

标签: python mysql sql-insert mysql-python

这些是表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,但它不起作用,任何人都可以告诉我解决方案

1 个答案:

答案 0 :(得分: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]));
相关问题