使用python插入sql数据库

ddrv8njm  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(477)

我想通过在python脚本中使用websocket将raspberry pi中的值放入笔记本电脑上的sql数据库。


# starting import MySQLdb

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","root","","cms",autocommit=True)

# prepare a cursor object using cursor() method

cursor = db.cursor()

from websocket import create_connection

ws = create_connection("ws://192.168.0.53:8080/websocket")

while True:
    result = ws.recv()
    print(result)
    spl = result.split(' ',1)
    boom_id2 = str(spl[0])
    boom_data = str(spl[1])

    sql = """INSERT INTO datain(boom_id2,boom_data)
             # VALUES ('""" + boom_id2 +"""', '""" + boom_data +"""')"""
    cursor.execute(sql)

db.close()
ws.close()

它返回一个错误:

Traceback (most recent call last):

  File "C:\Users\Ashraff\Desktop\Enginnering\test.py", line 26, in <module>
    cursor.execute(sql)
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler
    raise errorvalue
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\cursors.py", line 247, in execute
    res = self._query(query)
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\cursors.py", line 411, in _query
    rowcount = self._do_query(q)
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query
    db.query(q)
  File "C:\Users\Ashraff\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\connections.py", line 277, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2")
s4n0splo

s4n0splo1#

您的sql查询中有一个错误,应该是这样的

sql = ("""INSERT INTO datain(boom_id2,boom_data)
            VALUES (%s, %s)""", (boom_id2, boom_data))
   print(sql)
   cursor.execute(sql)

请尝试打印此sql查询并在本地服务器上运行,以检查查询是否正确

相关问题