Python pymySQL 发送带引号的字符串 [英] Python pymySQL sending a string with quotes

查看:66
本文介绍了Python pymySQL 发送带引号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 mySQL 数据库中插入一个字符串,如下所示:

I'm trying to insert a string to a mySQL database like this:

cur.execute('UPDATE connections SET cmd = "' + command + '", client_new = 1 where ip = "' + ip + '"')

当我将 command 设置为 echo "hello" 时,出现此错误:

When I set command to be echo "hello", I get this error:

Traceback (most recent call last):
  File "C:/Users/Owner/Desktop/master.py", line 111, in <module>
    main ()
  File "C:/Users/Owner/Desktop/master.py", line 80, in main
    print(""); command(); print("")
  File "C:/Users/Owner/Desktop/master.py", line 29, in command
    cur.execute('UPDATE connections SET cmd = "' + command + '", client_new = 1 where ip = "' + ip + '"')
  File "M:\Python34\lib\site-packages\pymysql\cursors.py", line 146, in execute
    result = self._query(query)
  File "M:\Python34\lib\site-packages\pymysql\cursors.py", line 296, in _query
    conn.query(q)
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 781, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 942, in _read_query_result
    result.read()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 1138, in read
    first_packet = self.connection._read_packet()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 906, in _read_packet
    packet.check_error()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 367, in check_error
    err.raise_mysql_exception(self._data)
  File "M:\Python34\lib\site-packages\pymysql\err.py", line 120, in raise_mysql_exception
    _check_mysql_exception(errinfo)
  File "M:\Python34\lib\site-packages\pymysql\err.py", line 112, in _check_mysql_exception
    raise errorclass(errno, errorvalue)
pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'hello"", client_new = 1 where ip = "123.456.789.012"\' at line 1')

我知道我将数据传递到数据库的方式存在问题,但我该如何正确执行?

I understand that there is a problem with how I'm passing the data to the database, but how do I do it properly?

推荐答案

您可以使用占位符,在这种情况下 mysql 驱动程序会转义您的查询:

You could use placeholders, in that case mysql driver escapes your query:

cur.execute('UPDATE connections SET cmd=%s, client_new=1 where ip=%s', (command, ip))

这篇关于Python pymySQL 发送带引号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆