Inserting data into a table in MySQL with PyMySQL
Question:
I tried to insert some data into a table like this as below, but it doesn’t work for me.
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8', db='kobis')
cur = conn.cursor()
sql = """insert into 'boxoffice' (targetDt, rank, rankOldAndNew,
movieCd, movieNm, salesAmt, audiCnt)
values (%d, %d, %s, %d, %s, %d, %d) % cur.execute(sql,
(20180220,11,'OLD',20170511,'Conan',36388900,48011))
"""
conn.commit()
There doesn’t come out any error message after running this code, but the new data I tried to insert doesn’t show up in the table ‘boxoffice’ at all…
Does anyone have a good idea to fix this?
Answers:
You need to execute your sql, you missed that line:
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8', db='kobis')
cur = conn.cursor()
sql = """insert into `boxoffice` (targetDt, rank, rankOldAndNew,
movieCd, movieNm, salesAmt, audiCnt)
values (%s, %s, %s, %s, %s, %s, %s)
"""
cur.execute(sql,(20180220,11,'OLD',20170511,'Conan',36388900,48011))
conn.commit()
EDIT
Yor cur.execute() was inside the sql
string, so it was doing nothing
for me the problem was not adding a n please do something like this:
sql = f"INSERT INTO audits ({fields})"+ "n" + f"VALUES ({values})"
I hope this helps others cracked my head on this issue for over 2 hours.
I tried to insert some data into a table like this as below, but it doesn’t work for me.
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8', db='kobis')
cur = conn.cursor()
sql = """insert into 'boxoffice' (targetDt, rank, rankOldAndNew,
movieCd, movieNm, salesAmt, audiCnt)
values (%d, %d, %s, %d, %s, %d, %d) % cur.execute(sql,
(20180220,11,'OLD',20170511,'Conan',36388900,48011))
"""
conn.commit()
There doesn’t come out any error message after running this code, but the new data I tried to insert doesn’t show up in the table ‘boxoffice’ at all…
Does anyone have a good idea to fix this?
You need to execute your sql, you missed that line:
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8', db='kobis')
cur = conn.cursor()
sql = """insert into `boxoffice` (targetDt, rank, rankOldAndNew,
movieCd, movieNm, salesAmt, audiCnt)
values (%s, %s, %s, %s, %s, %s, %s)
"""
cur.execute(sql,(20180220,11,'OLD',20170511,'Conan',36388900,48011))
conn.commit()
EDIT
Yor cur.execute() was inside the sql
string, so it was doing nothing
for me the problem was not adding a n please do something like this:
sql = f"INSERT INTO audits ({fields})"+ "n" + f"VALUES ({values})"
I hope this helps others cracked my head on this issue for over 2 hours.