Search code examples
pythonmysqldatabasepymysql

Inserting data into a table in MySQL with PyMySQL


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?


Solution

  • 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