0

These are the following entries in Table MyTable

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

This is the schema of 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    |                |
+-------+-------------+------+-----+---------+----------------+

While Executing the following code i am getting the following error

    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");

ERRORS:

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'")

I am trying to insert duplicate values but changing the primary key id , but it is not working can anyone tell me the solution

2
  • execute(''' why 3 single quotes open? Commented Oct 23, 2015 at 12:11
  • 1
    You either need to quote the strings in the query, or use a prepared query like in Alex's answer. Commented Oct 23, 2015 at 12:15

1 Answer 1

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]));
Sign up to request clarification or add additional context in comments.

3 Comments

File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute query = query % db.literal(args) TypeError: %d format: a number is required, not str
i am using %d which cant concatenate with a string so
i[0] is a string, but integer should be there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.