簡體   English   中英

將python變量插入mysql表的行

[英]Insert python variables into rows of mysql table

我有以下代碼可以解析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,日期,時間和狀態列。 我想將這些變量的數據插入到這些列下的表中。 (請注意,有三個單獨的傳感器,因此最后我將需要三行數據。)

當我運行它時,它不會插入到我的表中。 請幫忙! 謝謝。

您沒有將任何參數傳遞給查詢。

代替:

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在每個迭代步驟中調用INSERT數據庫查詢,不如考慮將數據收集到一個列表中,然后在循環后插入一次

希望能有所幫助。

將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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM