这是我的代码,我从MCP3008获取数据,我想将这些值写入SQL数据库,但它无法正常工作。当我执行代码时没关系,但是当我打开SQL数据库时它是空的。
Python程序:
spi = spidev.SpiDev()
spi.open(0,0)
def ReadChannel(channel):
adc = spi.xfer2([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data
TIMES = 480
def AdcRead(adc_value = []):
time_start = time.time()
i = 0
while True:
time_current = time.time()
if time_current > time_start + i / float(TIMES):
print('{}: {}'.format(i, time_current))
data = ReadChannel(0)
adc_value.append(data)
i += 1
if i > 223:
max_value = max(adc_value)
break
print(adc_value)
return max_value
amp = AdcRead() * 0.8
amp = amp + 0.0
print("Binario: {}").format(amp)
output = 240*(amp/1024)*30
print("Potennia: {}").format(output)
amp_out = output/240
print ("Amperes: {}").format(amp_out)
output_h = output/3600
price = output_h * 0.15
ts = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
db = MySQLdb.connect("localhost","root","pass","auto_room_control")
cursor = db.cursor()
sql = "INSERT INTO auto_room_control VALUES ('%s', '%d', '%d', '%d', '%d' )", (ts, amp_out, output, output_h, price)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
当我执行MySql命令时:
mysql> USE auto_room_control;
mysql> SELECT * FROM power_consumption;
Empty set (0.00 sec)
我得到了“空集(0.00秒)”。我做错了什么?
答案 0 :(得分:0)
有几个问题。
更改
sql = "INSERT INTO auto_room_control VALUES ('%s', '%d', '%d', '%d', '%d' )", (ts, amp_out, output, output_h, price)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
到
sql = "INSERT INTO auto_room_control VALUES (%s, %s, %s, %s, %s)"
sqldata = (ts, amp_out, output, output_h, price)
try:
cursor.execute(sql, sqldata)
db.commit()
except:
db.rollback()
因为%s
是由数据库驱动程序解释的,这是防止SQL注入的最简洁方法。
将其更改为
sql = "INSERT INTO auto_room_control VALUES (%s, %s, %s, %s, %s)"
sqldata = (ts, amp_out, output, output_h, price)
with db as cursor:
cursor.execute(sql, sqldata)
with语句单独进行提交和回滚。
答案 1 :(得分:-1)
问题在于:
sql = "INSERT INTO auto_room_control VALUES ('%s', '%d', '%d', '%d', '%d' )", (ts, amp_out, output, output_h, price)
你应该这样写:
sql = "INSERT INTO auto_room_control VALUES ('%s', %d, %d, %d, %d )" % (ts, amp_out, output, output_h, price)
在你的情况下,你只需创建几个字符串和另一对,而不是格式化。