使用Python插入SQL数据库

时间:2018-06-27 21:31:54

标签: mysql sql python-3.x websocket raspberry-pi

我想通过使用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")

1 个答案:

答案 0 :(得分:1)

您的SQL查询中有错误 应该是这样的

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

尝试打印此SQL查询并在本地服务器中运行它以检查查询是否正确