python mysql in 查询泽恩么给值加上引号
时间: 2023-05-04 07:04:03 浏览: 108
在Python与MySQL连接中使用SELECT查询时,如果要给值加上引号,需要使用字符串拼接的方法。例如,如果要查询name字段为John的数据,可以这样写:
```
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='dbname')
cursor = cnx.cursor()
name = 'John'
query = "SELECT * FROM tablename WHERE name = '" + name + "'"
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
cnx.close()
```
在上述例子中,使用了字符串拼接的方式,将查询条件中的name字段值John用引号括起来。这样可以确保查询条件被正确识别,并且保证了查询结果的准确性。同时,也可以使用参数化查询的方式来避免这个问题,例如:
```
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='dbname')
cursor = cnx.cursor()
name = 'John'
query = "SELECT * FROM tablename WHERE name = %s"
cursor.execute(query, (name,))
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
cnx.close()
```
在这个例子中,使用了参数化查询的方式,将查询条件中的name字段值作为参数传递给execute方法,而不是直接在SQL语句中拼接。这样可以避免SQL注入等安全问题。
阅读全文