我正在使用版本为3.xx的python。如您所知,在python 3.xx中没有MySQL库。由于这个原因,我试图使用pymysql连接我的数据库。使用pymysql时,无法插入数据库数据。(我是BEGINNER)。当我运行此脚本时,我得到了:
Traceback (most recent call last):
File "home/pi ......
cur.execute(sql)
Name:Error: cur is not defined.
我怎样才能解决这个问题 ?我如何定义cursor.execute?我为此打电话给图书馆,为什么我必须再次定义它?
这是我的代码。我删除了这个问题不需要的部分。
import os
import time
import datetime
import glob
import mysql.connector
from mysql.connector import errorcode
from time import strftime
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28-000008a43c0e')[0]
device_file = device_folder + '/w1_slave'
#---------------------------------------------------------------------------
#Connect MySQL
#---------------------------------------------------------------------------
cnx = mysql.connector.connect(user='root',password='mehmetali',
host='localhost',
database='temp-at-interrupt')
cursor= cnx.cursor()
#---------------------------------------------------------------------------
#Get Temperature Values.
#---------------------------------------------------------------------------
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
#---------------------------------------------------------------------------
#Insert new data
#---------------------------------------------------------------------------
if True:
temp=read_temp()
print(temp)
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
print (datetimeWrite)
#sql= ("""INSERT INTO `temp-at-interrupt` (Date,Time,Temperature) VALUES (%s,%s,%s )""",(datetimeWrite,temp))
sql = ("""INSERT INTO `temp-at-interrupt` (`Date`,`Time`,`Temperature`) VALUES ('%s','%s','%s' )""",(datetimeWrite,temp))
try:
print ("Writing to database...")
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
cnx.commit()
print ("Write Complete")
except:
# Rollback in case there is any error
cursor.close()
cnx.close()
print ("Failed writing to database")
更新:当我按照以下顺序进行操作:“您必须建立连接,定义光标,运行查询,并在完成查询后可以关闭连接。”我更正了我的错误。但是我仍然停留在这里。我的输出是这样的。
25.35 C
2018-04-20 22:21:04
Writing to Database...
Failed writing to database
我在哪里错了?
您误解了如何使用python接口。
cnx = mysql.connector.connect(user='root',password='******',
host='localhost',
database='temp-at-interrupt')
cnx.close()
在这里连接,然后关闭连接。此后,无需定义游标就cur
可以尝试使用它执行查询。这行不通。
您必须设置连接,定义光标,运行查询,完成查询后即可关闭连接。
mysql文档提供了这个例子,展示了它的流程:
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
tomorrow = datetime.now().date() + timedelta(days=1)
add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid
# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)
# Make sure data is committed to the database
cnx.commit()
cursor.close()
cnx.close()
在这里,您可以清楚地看到连接到数据库,创建游标,执行查询,将结果提交到数据库以及最后清理和关闭连接的流程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句