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?

Asked By: C. Shin

||

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

Answered By: nacho

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.

Answered By: d-dutchview
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.