python连接mysql示例一:
import pymysql
#连接数据库
con=pymysql.connect(host='localhost',database='test',port=3306,user='root',passwd='root',charset='utf8')
#获取一个和数据库交互的工具cursor
cursor=con.cursor()
#编写sql语句
user_id = "15" #传递参数
user_name = "hh" #传递参数
sql1='''INSERT INTO mytable VALUES(%s,'%s');''' % (user_id, user_name)
sql2='''INSERT INTO mytable VALUES(%s,%s);'''
args = [(24,'kk'),(25,'kk'),(26,'kk')] #用列表或者元组传递参数
sql3='''SELECT * FROM mytable LIMIT %s;''' % 40 #传递参数
#使用coursor的方法执行语句
try:
# 执行sql语句
cursor.execute(sql1)
cursor.executemany(sql2,args) #使用executemany同事执行多条数据
# python中DML操作需要提交事务
con.commit()
cursor.execute(sql3)
result = cursor.fetchall()
"""
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall(): 接收全部的返回结果行
fetchmany(num):查询指定条数的记录
#rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。接收全部的返回结果行
"""
#遍历结果集合打印
for i in result:
print(f"用户编号是{i[0]},名称是{i[1]}")
except BaseException as errorm: #抛出错误原因
# 如果发生错误则回滚
con.rollback()
print("error:",errorm)
#关闭coursor
cursor.close()
#关闭连接数据库
con.close()
由此探讨一个防止SQL输入漏洞的问题
比如,这里要求,查询结果必须符合id和name同时正确,才能输出用户信息,但是因为输入了sql的关键字符#,导致第二个验证失效。
关键在于避免使用拼接字符串,将参数带入执行
# 执行sql语句 cursor.execute(sql3,(id,name))
以下两个方法比对测试:
import pymysql
def mysqlcon(id,name):
#连接数据库
con=pymysql.connect(host='localhost',database='test',port=3306,user='root',passwd='root',charset='utf8')
#获取一个和数据库交互的工具cursor
cursor=con.cursor()
#编写sql语句
sql3='SELECT * FROM mytable where id=' ' '+id+' '' and name="'+name+'" LIMIT 40;'
print(sql3)
#使用coursor的方法执行语句
try:
# 执行sql语句
cursor.execute(sql3)
result = cursor.fetchall()
#遍历结果集合打印
for i in result:
print(f"用户成功输出:编号是{i[0]},名称是{i[1]}")
except BaseException as errorm: #抛出错误原因
# 如果发生错误则回滚
con.rollback()
print("error:",errorm)
#关闭coursor
cursor.close()
#关闭连接数据库
con.close()
def mysqlcon2(id,name):
#连接数据库
con=pymysql.connect(host='localhost',database='test',port=3306,user='root',passwd='root',charset='utf8')
#获取一个和数据库交互的工具cursor
cursor=con.cursor()
#编写sql语句
sql3='SELECT * FROM mytable where id=%s and name=%s LIMIT 40;'
print(sql3)
#使用coursor的方法执行语句
try:
# 执行sql语句
cursor.execute(sql3,(id,name))
result = cursor.fetchall()
print(result)
#遍历结果集合打印
for i in result:
print(f"用户编号是{i[0]},名称是{i[1]}")
except BaseException as errorm: #抛出错误原因
# 如果发生错误则回滚
con.rollback()
print("error:",errorm)
#关闭coursor
cursor.close()
#关闭连接数据库
con.close()
if __name__=="__main__":
mysqlcon('1', 'BB') #结果正确
mysqlcon('1 and 1=1 # ','AA') #输入错误却仍获取数据
mysqlcon2('1', 'BB') #结果正确
mysqlcon2('1 and 1=1 # ', 'AA') #输入错误不会再获得数据
测试结果: