Я использую python версии 3.x.x. В python 3.x.x, как вы знаете, нет библиотеки для MySQL. По этой причине я пытаюсь использовать pymysql для подключения моей базы данных. При использовании pymysql я не могу вставить данные в свою базу данных. (Я НАЧИНАЮЩИЙ). Когда я запустил этот скрипт, я получил:
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()
Здесь Вы ясно видите поток соединения с базой данных, создания курсора, выполнения запросов, передачи результата к DB, и наконец чистки и закрытия соединения.
Ваш оператор вставки пытается вставить 3 значения (Дата, Время, Температура), но Вы предоставляете только 2 (datetimeWrite, временный файл). Это не может работать. Кроме того, как обозначено vidarlo, действительно необходимо изучить ошибки. Просто помещение оператора печати, обозначенного в ссылке, может помочь Вам много:
...
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
...