Python Day 41 Mysql 基础语法(三)

  ##Navicat介绍

#生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具

#下载链接:https://pan.baidu.com/s/1bpo5mqj

掌握:
#1. 测试+链接数据库
#2. 新建库
#3. 新建表,新增字段+类型+约束
#4. 设计表:外键
#5. 新建查询
#6. 备份库/表

#注意:
批量加注释:ctrl+?键
批量去注释:ctrl+shift+?键


#尽量少用这种可视化的东西,不然后期sql语句全忘了

   ##pymysql模块

#1、安装
pip3 install pymysql


#2、链接、执行sql、关闭(游标)
import pymysql
user=input('用户名: ').strip()
pwd=input('密码: ').strip()

#链接
conn=pymysql.connect(host='localhost',user='root',password='123',database='egon',charset='utf8')
#游标
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
#执行sql语句
sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号
cursor.execute(sql)

# res = cursor.fetchone()#获取一行
res = cursor.fetchmany(10)#获取多行
# res = cursor.fetchall()  ### 列表里面套字典,获取全部
#print(res)

#关闭游标、连接
cursor.close()
conn.close()

if res:
    print('登录成功')
else:
    print('登录失败')

#3、上面的sql语句存在sql注入的问题
登录验证问题        
    写sql语句的时候, %传值的时候, 需要加引号:
        sql = "select * from t4 where name = '%s' and pwd = '%s'" % (username, pwd)
    
    上面的sql语句带来的风险是:
    
        例一:
            username = zekai' #
            
            select * from t4 where name = 'zekai' #' and pwd = ''
        
        例二:
            username = dbsahvbdsha' or 1=1 #
            
            select * from t4 where name = 'dbsahvbdsha' or 1=1 
        
    上面出现的问题,我们称之为 SQL注入  (**********************************)
    
    出现问题的根源是:
        
        因为太过于相信用户的输入, 导致我们在接受用户输入的参数的时候, 并没有对他进行转义
    
    解决SQL注入:
        
        1. 自己手工对用户输入的值进行转义
        
        2. 使用execute()自动进行过滤
        
            sql = "select * from t4 where name = %s and pwd = %s" 

            cursor.execute(sql,(username, pwd))
    
    #$## 插入一条
    cursor.execute(sql, ('lxxx', '1234'))

    ### 插入多条
    data = [
        ('aaaaa', 'aaa'),
        ('bbbb', 'bbb'),
        ('ffff', '666'),
        ('rrrr', '888'),
    ]
    cursor.executemany(sql, data)


    try:
        cursor.execute(sql, ('lxxx', '1234'))
        
        ###  删除和更新的时候, 需要事物提交
        conn.commit()
    except Exception as e:
        conn.rollback()


    cursor.lastrowid : 最后一行的行数
#4、插入删除操作:需要提交哦
import  pymysql,time

# 连接mysql服务器

conn = pymysql.connect(host='localhost', user='root', password='123',database='db1', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# sql = "delete from t7 where id=%s"

#sql = "delete from t7 where id=3"
sql = "insert into t4 (name, pwd) values (%s, %s)"



# ### 插入多条
data = [
    ('aaaaa', 'aaa'),
    ('bbbb', 'bbb'),
    ('ffff', '666'),
    ('rrrr', '888'),
]
cursor.executemany(sql, data)

#$## 插入一条
# try:
#     cursor.execute(sql, ('gggg', '1234'))
#     ###  删除和更新的时候, 需要事物提交
#     conn.commit()
# except Exception as e:
#     conn.rollback()


conn.commit()
print(cursor.lastrowid)
# print(conn.insert_id())



cursor.close()
conn.close()

猜你喜欢

转载自www.cnblogs.com/liangzhenghong/p/11027705.html