将python变量插入mysql表的行中

时间:2014-03-18 03:47:15

标签: python mysql sql

我有以下代码来解析XML文件中的数据。

import MySQLdb
from xml.dom import minidom

xmldoc = minidom.parse("report.xml")

parking_report = xmldoc.getElementsByTagName("parking_report")[0]

sensors = parking_report.getElementsByTagName("sensor")

for sensor in sensors:
    id = sensor.getElementsByTagName("id")[0].firstChild.data
    date = sensor.getElementsByTagName("date")[0].firstChild.data
    time = sensor.getElementsByTagName("time")[0].firstChild.data
    status = sensor.getElementsByTagName("status")[0].firstChild.data

    db = MySQLdb.connect(host="localhost",user="root",passwd="pass",db="parking_report")
    cur = db.cursor()
    cur.execute('INSERT INTO report_table (id, date, time, status) VALUES (id, date, time, status)')

    print(id, date, time, status)

现在,它运行时没有错误,并返回每个停车传感器的ID,日期,时间和状态。但是,我的mySQL表(parking_report)也有列ID,日期,时间和状态。我想在这些列下将这些变量的数据插入到我的表中。 (注意有三个独立的传感器,所以最后我需要三行数据。)

当我运行它时,它不会插入到我的表中。请帮忙!谢谢。

2 个答案:

答案 0 :(得分:1)

您没有将任何参数传递给查询。

而不是:

cur.execute('INSERT INTO report_table (id, date, time, status) VALUES (id, date, time, status)')

创建参数化查询:

cur.execute("""INSERT INTO 
                   report_table 
                   (id, date, time, status) 
               VALUES
                   (%(id)s, %(date)s, %(time)s, %(status)s)""", 
            {'id': id, 
             'date': date, 
             'time': time, 
             'status': status})

您应该对代码应用其他修补程序:

  • 在循环之前定义dbcursor变量,这样您就不需要连接到数据库并在每次迭代时打开游标
  • 您应该正确关闭游标和连接对象
  • 而不是在每个迭代步骤调用INSERT数据库查询,考虑将数据收集到列表中,然后在循环后插入一次

希望有所帮助。

答案 1 :(得分:0)

将python变量插入mysql表行的最简单方法是:

cursor.execute(
   """INSERT INTO menu(col1, col2, col3) VALUES(%s, %s, %s)"""
   %(item1, item2, item3))

在你的情况下:

cursor.execute(
   """INSERT INTO report_table(id, date, time, status) VALUES(%s, %s, %s, %s)"""
   %(id, date, time, status))