python连接mysql示例

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') #输入错误不会再获得数据

测试结果:

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值