9

如果记录已经存在,我需要更新一行,如果不存在,我需要创建一个新记录。我不知道 ON DUPLICATE KEY 将使用 MYSQLdb 完成此操作,但是我无法使其正常工作。我的代码如下

        cursor = database.cursor()
        cursor.execute("INSERT INTO userfan (user_id, number, round VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE user_id =%s, number=%s, round=%s", (user_id, number, round))
        database.commit()

主键是 user_id

4

2 回答 2

20

缺少一个括号。您还可以在语句VALUES(column)ON DUPLICATE KEY UPDATE部分中使用:

    cursor = database.cursor()
    cursor.execute("""
        INSERT INTO userfan 
            (user_id, number, round)
        VALUES 
            (%s, %s, %s) 
        ON DUPLICATE KEY UPDATE 
                                          -- no need to update the PK
            number  = VALUES(number), 
            round   = VALUES(round) ;
                   """, (user_id, number, round)     # python variables
                  )
    database.commit()
于 2013-03-17T20:11:37.580 回答
0
def insertAndUpdateData(lVideoList, no_of_gate):
    connection = sqlite3.connect('db.sqlite',
                                 detect_types=sqlite3.PARSE_DECLTYPES |
                                              sqlite3.PARSE_COLNAMES)
    cursor = connection.cursor()
    success = 200
    unsuccess = 500
    default_value = 0
    lDefaultEntry = None
    for i in range(no_of_gate):
        gate_id = i+1
        for videofilename in lVideoList:            
            cursor.execute("SELECT * FROM dailyfootfall WHERE csv_name=? AND gate_id=?", [videofilename, gate_id])
            lDefaultEntry = cursor.fetchone()
            try:
                
                if lDefaultEntry is not None:
                    
                    print ('Entry found...!!!')

                    cursor.execute("UPDATE dailyfootfall SET video_download=?, processed=?, send_status=? ,male_footfall=?, send_status_male=?, "
                                   "female_footfall =?,send_status_female=?, outsiders=?, send_status_outsiders=? "
                                   "WHERE csv_name=? AND gate_id=? AND footfall=0", [unsuccess,unsuccess,unsuccess,default_value,unsuccess,
                                                                                    default_value,unsuccess,default_value,unsuccess,videofilename,gate_id])
                    print("Data_Updated..!!!")
                    
                else:
                    cursor = connection.cursor()
                    print ('Entry Not found...!!!')
                    print("videofilename: ", videofilename)
                    insert_query = ("INSERT or IGNORE INTO dailyfootfall(csv_name, video_download, processed, footfall, send_status, "
                                    "male_footfall, send_status_male, female_footfall, send_status_female, gate_id,outsiders, send_status_outsiders) "
                                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)")

                    cursor.execute(insert_query,[videofilename, unsuccess, unsuccess, default_value, unsuccess, default_value,
                                                 unsuccess, default_value, unsuccess, gate_id, default_value, unsuccess])

                    print("Data_Inserted..!!")
                    print("="*20)
                    
                
                
            except Exception as e:
                
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                print("Entry found: ",exc_type, fname, exc_tb.tb_lineno)
                
    print("Data Inserted Successfully !")
    connection.commit()
    cursor.close()
    connection.close()

if __name__ == "__main__":

  
    lVideoList = ['2022_01_27_10_00_00-2022_01_25_10_30_00', '2022_01_27_10_30_00-2022_01_25_11_00_00',
                '2022_01_27_11_00_00-2022_01_25_11_30_00', '2022_01_27_11_30_00-2022_01_25_12_00_00']
    no_of_gate = 3


    UpdateData(lVideoList, no_of_gate)


    print("default_value inserted!!!!")
于 2022-01-27T12:13:39.707 回答