首页 > 解决方案 > Run second execute command if first execute command is successful

问题描述

I am trying to make my code not loop the whole entire thing over and over, I am trying to make it stop and loop only the first execute if nothing happens there. The function at execute command 1 is it reads data from a card and stores it into the db. This is the current if statement I am trying to use with the code:

EDIT currently the comman2 is executed first followed by c1 and the program keeps looping even if there is no input I am trying to make the first execute(command2) to stay at comman2 if there is no input and only move to c1 (second execute) when there is input

import serial
from datetime import datetime, timedelta
ser = serial.Serial('COM4',9600)

print("Serial input ready..")
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="rfid",
  passwd="rfidpasswd",
  database="rfid"
)
mycursor = mydb.cursor()    
try:
  while True:
    line = ser.readline().strip()
    l= line
    data = line.decode('ascii').split(':')
    rid = data[0]
    tag = data[1]
    t = datetime.now() -timedelta(minutes = 190 )

    command2 = "INSERT INTO tag_logs (reader_id, tag_no) VALUES ('" +rid+ "','" +tag+ "')"
    mycursor.execute(command2)
    mydb.commit() 

    c1 = "Select * From tag_logs where reader_id = 'Reader_001' and timestamp > '" + str(t) +"' and tag_no = '"+tag+"'"

    print(c1)

    n=mycursor.execute(c1)


    result1 = mycursor.fetchall()
    print((n))
    print (len(result1))
    x= (len(result1))

    mycursor = mydb.cursor(buffered=True)

    if x > 0:   
       ser.write(b'H')
       print('done')


    else:

      ser.write(b'L')
      print('deny')

    if l == 1:
      n=mycursor.execute(c1)

    else:
      mycursor.execute(command2)


except KeyboardInterrupt:
  pass

标签: pythonmysqlif-statement

解决方案


推荐阅读