mysql数据库模块下载_MySQL 数据库连接 - PyMySQL模块

一、什么是 PyMySQL?

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

二、PyMySQL 安装

在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。

如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:

cmd命令:pip3 install PyMySQL

三、数据库连接

#代码链接

importpymysql#链接

conn=pymysql.connect(

host='localhost',

user='root',

password='123',

database='egon',

charset='utf8')#游标

cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示

#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) # 以字典的方式显示数据

四、操作数据库

#pymysql操作数据库

#执行sql语句

user= input(">>>:").strip()

pwd= input(">>>:").strip()

sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号

rows=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目

'''获取真实数据,类似管道取值,

cursor.fetchone(),获取一条

cursor.fetchall(),所有

cursor.fetchmany(),多条'''cursor.scroll(1,'relative') #相对移动,从当前位置移动cursor.scroll(3,'absolute') #绝对移动,从数据管道开始位置移动

cursor.close()

conn.close()

五、关于sql注入问题

所谓SQL注入,就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令;

如果通过网页获取用户输入的数据并将其插入一个MySQL数据库,那么就有可能发生SQL注入安全的问题。

importpymysql

conn=pymysql.connect(

host= '127.0.0.1',

port= 3306,

user= 'root',

password= '123',

database= 'test',

charset= 'utf8',

autocommit=True

)

cursor=conn.cursor(pymysql.cursors.DictCursor)

username= input('username>>>:')

password= input('password>>>:')

sql= "insert into userinfo(name,password) values(%s,%s)"

'''

sql = "update userinfo set name='jasonhs' where id =1"sql = "select * from userinfo where name=%s and password=%s"

'''

res =cursor.execute(sql,(username,password))#res = cursor.execute(sql)#conn.commit() # 确认数据无误之后 commit之后才会将数据真正修改到数据库

print(sql)ifres:#print(cursor.fetchall())

pass

else:print('用户名或密码错误!')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值