在python中使用for循环生成mySQL插入语句

时间:2015-09-18 16:59:05

标签: python mysql

我正在研究一个python脚本,从几个arduinos中获取传入的数据字符串,以读取,拆分并将数据插入到数据库中。

问题是传感器数据的数量会根据使用的传感器类型而有所不同。我无法弄清楚正确的方法来循环分离的碎片并正确插入它们。

A' 1'指定10HS传感器,输入值需要1个空格
对于10HS传感器,String就像这样:
" Cucumber2015,Arduino01,1,20150918124200,25.3,75.5, 1 ,12 .....

A' 2'指定10HS传感器,输入值需要1个空格
" Cucumber2015,Arduino01,1,20150918124200,25.3,75.5, 2 ,12,24,23 ......

for循环应该重复,直到所有传感器值都有各自表的insert语句。

我已经尝试了下面显示的代码并继续收到错误。

我怎样才能做到这一点?除了语法问题,我还能正确地解决这个问题吗?

我当前的错误

  File "serialToDbV3.py", line 50
    index =index+1
        ^
SyntaxError: invalid syntax

Python代码

#!/usr/bin/python

import serial 
import MySQLdb

#establish connection to MySQL. You'll have to change this for your database.
dbConn =     MySQLdb.connect("localhost","python_user","password","IrrigationDB") or die ("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()

device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
baudrate = 9600

def getSerialData():
try:
    print "Trying...",device
    arduino = serial.Serial(device, baudrate) 
except: 
    print "Failed to connect on",device    

try:
    print "Trying to get data"
    next(arduino)
    data = arduino.readline()  #read the data from the Arduino
    pieces = data.split(",")  #split the data by the tab
    print "Data: %s" % data
    print "Piece 0: ProjectID %s" % pieces[0]
    print "Piece 1: ArduinoID %s" % pieces[1]
    print "Piece 2: Plot#     %s" % pieces[2]
    print "Piece 3: SQLTime   %s" % pieces[3]
    print "Piece 4: AirTemp   %s" % pieces[4]
    print "Piece 5: Humidity  %s" % pieces[5]
    print "Piece 6: SensType  %s" % pieces[6]
    print "Piece 7: SensData  %s" % pieces[7]
    print "Piece 8:           %s" % pieces[8]
    print "Piece 9:          %s" % pieces[9]
    print "Piece 10:          %s" % pieces[10]
#Here we are going to insert the data into the Database
    try:
        print "Trying insertion..."
        cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Project`(`idProject`)VALUES (%s)", (pieces[0]))     
        cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Arduino`(`idArduino`,`FK_ProjectID`)VALUES (%s,%s)", (pieces[1],pieces[0]))     
        cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Plot`(`idPlot`,`FK_ArduinoID`)VALUES (%s,%s)", (pieces[2],pieces[1]))       
        cursor.execute("INSERT INTO `IrrigationDB`.`Reading`(`DateAndTime`,`airTempC`,`relativeHumidity`,`FK_PlotID`)VALUES (%s,%s,%s,%s)", (pieces[3],pieces[4],pieces[5],pieces[2]))       

        startingPosition = 6
        for index in xrange(startingPosition, len(pieces), step):
            if pieces[6] == 1 :
                cursor.execute("INSERT INTO `IrrigationDB`.`10HS_Sensor`(`id10HS_Sensor`,`DielectricPermittivity`)VALUES (%s,%s,%s)", (pieces[2],pieces[i+1])
                index =index+1
            if pieces[6] == 2 :
                cursor.execute("INSERT INTO `IrrigationDB`.`GS3_Sensor`(`idGS3_Sensor`,`DielectricPermittivity`,`soilTempC`,`electricalConductivity`)VALUES (%s,%s,%s)", (pieces[2],pieces[i+1],pieces[i+2],pieces[i+3]))
                index=index+3
    except MySQLdb.IntegrityError:
        print "failed to insert data"         
except:
    print "Failed to get data from Arduino!" 

val = 0
while val == 0 :
    getSerialData()

1 个答案:

答案 0 :(得分:0)

使用适当的异常报告,至少在您到达最终用户土地之前。

try:
    cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Project`(`idProject`)VALUES (%s)", (pieces[0]))     
except Exception, e:
    print "this is sql #6", e
    raise

这将更清楚地告诉您发生了什么,然后您可以在此处发布。