首先咱们定义一个类来处理mysql的操作
class Database:
hostname = '127.0.0.1'
user = 'root'
password = 'root'
db = 'pythontab'
charset = 'utf8'
def init(self):
self.connection = MySQLdb.connect(self.hostname, self.user, self.password, self.db, charset=self.charset)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection测试数据mit()
except Exception, e:
print e
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(query)
return cursor.fetchall()
def del(self):
self.connection.close() 为了验证问题的真实性,这里就写一个方法来调用上面的那个类里面的方法,如果出现错误会直接抛出异常。
def test_query(testUrl):
mysql = Database()
try:
querySql = "SELECT * FROM `article` WHERE url='" + testUrl + "'"
chanels = mysql.query(querySql)
return chanels
except Exception, e:
print e (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 ''t.tips''' at line 1")
回显报错,很眼熟的错误,这里我传入的测试参数是
t.tips'
下面再说一种导致注入的情况,对上面的方法进行稍微修改后
def test_query(testUrl):
mysql = Database()
try:
querySql = ("SELECT * FROM `article` WHERE url='%s'" % testUrl)
chanels = mysql.query(querySql)
return chanels
except Exception, e:
print e 修改后的代码
class Database:
hostname = '127.0.0.1'
user = 'root'
password = 'root'
db = 'pythontab'
charset = 'utf8'
def init(self):
self.connection = MySQLdb.connect(self.hostname, self.user, self.password, self.db, charset=self.charset)
self.cursor = self.connection.cursor()
def insert(self, query, params):
try:
self.cursor.execute(query, params)
self.connection测试数据mit()
except Exception, e:
print e
self.connection.rollback()
def query(self, query, params):
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(query, params)
return cursor.fetchall()
def del(self):
self.connection.close() preUpdateSql = "UPDATE `article` SET title=%s,date=%s,mainbody=%s WHERE id=%s"
mysql.insert(preUpdateSql, [title, date, content, aid])
这样就可以防止sql注入,传入一个列表之后,MySQLdb模块内部会将列表序列化成一个元组,然后进行escape操作。
以上就是使用Python如何防止sql注入的方法的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于使用Python如何防止sql注入的方法的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did85591