Executemany无法正常工作(向mysql添加数据)

时间:2015-04-24 09:50:50

标签: python mysql

您好我一直在尝试使用execute many向mysql添加数据。我花了几个小时搜索和尝试,但它不起作用。 这是我的代码的一部分:

values = [("BEAFS","RBS00167","167","A1","BSC","RADIO X-CEIVER   ADMINISTRATION" ,"2015-04-07 12:10:00" ,"FUEL TANK ALARM G167-KARTERES")]   

db = MySQLdb.connect("localhost","root","","alarmsdb")
cursor = db.cursor()
sql = """INSERT INTO ALARMS_VF (elem_name, cell_name, site_no, alarm_severity,ne_type, alarm_name, alarm_raised_time, location_info) \
                               VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')""" #% (elem_name, cell_name, site_no, alarm_severity, ne_type, alarm_name, date, alarms)

   try:
      cursor.executemany(sql,values)
      db.commit()
   except:
      db.rollback()
 db.close()

我已经尝试了所有内容execute正常工作但executemany未插入数据。我尝试使用列表,元组,列表与元组但没有工作。即使有一个记录要测试它也不会插入任何内容。

1 个答案:

答案 0 :(得分:0)

我想驼鹿的第一个答案是正确的。但我使用了评论#%(elem_name,cell_name,site_no,alarm_severity,ne_type,alarm_name,date,alarm)的组合,我感到很困惑,因为我试图想错误和出了什么问题。现在无论如何都有效:

values = [("BEAFS","RBS00167","167","A1","BSC","RADIO X-CEIVER ADMINISTRATION" ,"2015-04-07 12:10:00" ,"FUEL TANK ALARM G167-KARTERES")]  
                if alarm_name.startswith("RADIO X") and alarms != '' or alarm_name.startswith("CELL LOGICAL"):
                    db = MySQLdb.connect("localhost","root","","alarmsdb")
                    cursor = db.cursor()
                    sql = """INSERT INTO ALARMS_VF (elem_name, cell_name, site_no, alarm_severity,ne_type, alarm_name, alarm_raised_time, location_info) \
                               VALUES ( %s, %s, %s, %s, %s, %s, %s, %s)""" #% (elem_name, cell_name, site_no, alarm_severity, ne_type, alarm_name, date, alarms)

                    #try:
                    cursor.executemany(sql,values)
                    db.commit()
                    #except:
                        #db.rollback()
                    db.close()

谢谢大家的帮助