python数据库特殊字符转义,Python MySQL转义特殊字符

本文介绍了一种使用Python向MySQL数据库插入包含特殊字符字符串的方法。通过采用参数绑定而非字符串格式化的方式,可以有效避免SQL语法错误及提升安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am using python to insert a string into MySQL with special characters.

The string to insert looks like so:

macaddress_eth0;00:1E:68:C6:09:A0;macaddress_eth1;00:1E:68:C6:09:A1

Here is the SQL:

UPGRADE inventory_server

set server_mac = macaddress\_eth0\;00\:1E\:68\:C6\:09\:A0\;macaddress\_eth1\;00\:1E\:68\:C6\:09\:A1'

where server_name = 'myhost.fqdn.com

When I execute the update, I get this error:

ERROR 1064 (42000):

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 'UPGRADE inventory_server

set server_mac = 'macaddress\_eth0\;00\:1E\:68\:C6\:09\' at line 1

The python code:

sql = 'UPGRADE inventory_server set server_mac = \'%s\' where server_name = \'%s\'' % (str(mydb.escape_string(macs)),host)

print sql

try:

con = mydb.connect(DBHOST,DBUSER,DBPASS,DB);

with con:

cur = con.cursor(mydb.cursors.DictCursor)

cur.execute(sql)

con.commit()

except:

return False

How can I insert this text raw?

解决方案

This is one of the reasons you're supposed to use parameter binding instead of formatting the parameters in Python.

Just do this:

sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s'

Then:

cur.execute(sql, macs, host)

That way, you can just deal with the string as a string, and let the MySQL library figure out how to quote and escape it for you.

On top of that, you generally get better performance (because MySQL can compile and cache one query and reuse it for different parameter values) and avoid SQL injection attacks (one of the most common ways to get yourself hacked).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值