无法将python和pymysql一起使用插入数据mysql

内约德·内斯特罗姆(NjordNyström)

我正在使用版本为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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Ajax / PHP / MySQL:将数据插入db不能与Ajax和PHP一起使用

来自分类Dev

将Supertest与Mock-fs和Jest一起使用时无法发布数据

来自分类Dev

PDO插入MySQL数据库无法与另一个PDO查询一起使用

来自分类Dev

如何将Spring Boot与MySQL数据库和JPA一起使用?

来自分类Dev

将MSSQL和MySQL与CodeIgniter一起使用

来自分类Dev

django将无法与python3.3.3一起使用

来自分类Dev

将gpointer与Python和GObject自省一起使用

来自分类Dev

将gpointer与Python和GObject自省一起使用

来自分类Dev

MySQL无法与Laravel一起使用

来自分类Dev

一起使用MySQL和MongoDB

来自分类Dev

我可以将glmnet与插入符号和稀疏矩阵一起使用吗?

来自分类Dev

Mysql group_concat与插入和限制一起使用时的行为

来自分类Dev

RWeka无法与插入符号或%dopar%一起使用

来自分类Dev

如何使用Linux Shell脚本和Python脚本一起插入空白行?

来自分类Dev

Oracle数据源连接池无法与Spring和JDBCTemplate一起使用

来自分类Dev

过滤Firebase数据时where()和orderBy()过滤器无法一起使用

来自分类Dev

在UI上对数据进行排序和渲染无法与React挂钩一起使用

来自分类Dev

无法将NSURLConnection与GCD一起使用来获取数据

来自分类Dev

java.sql.PreparedStatement.executeUpdate()无法与mysql数据库一起使用

来自分类Dev

为什么sqlalchemy可以与从jupter笔记本插入雪花和python连接器的插入一起使用?

来自分类Dev

无法将GeoJSON与Elasticsearch 5和Kibana 5一起使用

来自分类Dev

无法同时将Swift和Obj-C库与Cocoapods一起使用

来自分类Dev

无法将ng-bootstrap与Webpack和Angular2一起使用

来自分类Dev

无法将==与livedata <int>和int一起使用,我还能如何检查?

来自分类Dev

无法将GeoJSON与Elasticsearch 5和Kibana 5一起使用

来自分类Dev

无法将UISegmentedControl与三个选项卡和ContainerView一起使用

来自分类Dev

将 prune 和 -out 与 find 命令一起使用无法排除目录

来自分类Dev

将CTE与分层数据和“累积”值一起使用

来自分类Dev

将Streams与原始数据类型和相应的包装一起使用

Related 相关文章

  1. 1

    Ajax / PHP / MySQL:将数据插入db不能与Ajax和PHP一起使用

  2. 2

    将Supertest与Mock-fs和Jest一起使用时无法发布数据

  3. 3

    PDO插入MySQL数据库无法与另一个PDO查询一起使用

  4. 4

    如何将Spring Boot与MySQL数据库和JPA一起使用?

  5. 5

    将MSSQL和MySQL与CodeIgniter一起使用

  6. 6

    django将无法与python3.3.3一起使用

  7. 7

    将gpointer与Python和GObject自省一起使用

  8. 8

    将gpointer与Python和GObject自省一起使用

  9. 9

    MySQL无法与Laravel一起使用

  10. 10

    一起使用MySQL和MongoDB

  11. 11

    我可以将glmnet与插入符号和稀疏矩阵一起使用吗?

  12. 12

    Mysql group_concat与插入和限制一起使用时的行为

  13. 13

    RWeka无法与插入符号或%dopar%一起使用

  14. 14

    如何使用Linux Shell脚本和Python脚本一起插入空白行?

  15. 15

    Oracle数据源连接池无法与Spring和JDBCTemplate一起使用

  16. 16

    过滤Firebase数据时where()和orderBy()过滤器无法一起使用

  17. 17

    在UI上对数据进行排序和渲染无法与React挂钩一起使用

  18. 18

    无法将NSURLConnection与GCD一起使用来获取数据

  19. 19

    java.sql.PreparedStatement.executeUpdate()无法与mysql数据库一起使用

  20. 20

    为什么sqlalchemy可以与从jupter笔记本插入雪花和python连接器的插入一起使用?

  21. 21

    无法将GeoJSON与Elasticsearch 5和Kibana 5一起使用

  22. 22

    无法同时将Swift和Obj-C库与Cocoapods一起使用

  23. 23

    无法将ng-bootstrap与Webpack和Angular2一起使用

  24. 24

    无法将==与livedata <int>和int一起使用,我还能如何检查?

  25. 25

    无法将GeoJSON与Elasticsearch 5和Kibana 5一起使用

  26. 26

    无法将UISegmentedControl与三个选项卡和ContainerView一起使用

  27. 27

    将 prune 和 -out 与 find 命令一起使用无法排除目录

  28. 28

    将CTE与分层数据和“累积”值一起使用

  29. 29

    将Streams与原始数据类型和相应的包装一起使用

热门标签

归档