0

I have the following cell in jupyter (python3):

import pymysql


conn = pymysql.connect(host='localhost', port=3306, user='root',passwd='geheim', db='mysql')
cur = conn.cursor()
cur.execute("DROP DATABASE IF EXISTS foobar")
cur.execute("CREATE DATABASE foobar")
cur.close()
conn.commit()
conn.close()

conn = pymysql.connect(host='localhost', port=3306, user='root',passwd='geheim', db='foobar')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS map")
cur.execute("CREATE TABLE map (name varchar(64), ID integer, Parent_ID integer)")


map = (("A",1,2),
    ("B",4,5),
    ("C",0,0))

print (len(map))

for name,item_id, parent_ID in map:
    print (name, item_id, parent_ID)
    cur.execute("INSERT INTO map VALUES (\"" + name + "\"," + `item_id` + "," + `parent_ID` + ")")

cur.execute("SELECT * FROM map");
print (cur.fetchall())
cur.close()
conn.commit()
conn.close()
# to toggle linenumbers use CTRL-M L

I believe to recall that the code (INSERT statement) worked under python 2.7. Now, after conversion to python 3.5 I'm getting an error at the first backtic in the INSERT statement.

I used the backtick in python 2.7 to convert implicitly from the int to string.

Any clues how this would work correctly in python3?

Krischu
  • 1,024
  • 2
  • 15
  • 35
  • You really shouldn't create SQL by concatenating strings like that anyway. Use parameterized queries. – Wooble Jul 06 '16 at 14:34

1 Answers1

0

I found that ` was used in python 2.7 as an intrinsic to retrieve the representation of an object which was (ab?)used in the INSERT statement to convert the int to a string. In python 3 one has to use repr(object)

The INSERT statement now works using the following line: cur.execute("INSERT INTO map VALUES (\"" + name + "\"," + repr(item_id) + "," + repr(parent_ID) + ")")

Krischu
  • 1,024
  • 2
  • 15
  • 35