15-8 pymysql的使用
2024-08-31 21:01:27
一 安装pymysql模块
1 pycharm安装
file-setting如图:然后点加号,搜索pymsql即可,点击安装
2 pip 安装
pip3 install pymysql
二 连接数据库
import pymysql
user=input('用户名:').strip()
pwd=input('密码:').strip()
#连接数据库
conn=pymysql.connect(host='localhost',user='root',password='',database='user',charset='utf8')
#游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示 #执行sql语句
sql="select * from t1 where name=%s and pwd=%s"
print(sql)
res=cursor.execute(sql,[user,pwd]) #执行sql语句,返回sql查询成功的记录数目
#print(res) cursor.close()
conn.close() if res:
print('登录成功')
else:
print('登录失败')
执行上面的代码,返回
用户名:egon
密码:123
select * from t1 where name=%s and pwd=%s
登录成功
三 fetchone,fetchmany,fetchall
例子:
import pymysql
# username=input('请输入用户名:')
# pwd=input('请输入密码:') #连接数据库
conn = pymysql.connect(host='localhost',user='root',password='',db='user') #创建游标
cursor=conn.cursor()
#增
sql="select * from t1"
rows=cursor.execute(sql)
# res1=cursor.fetchone() #fetchone查看一行记录
# res2=cursor.fetchone()
# res3=cursor.fetchone()
# res4=cursor.fetchmany(2)#查看两行,以元祖形式出现
res5=cursor.fetchall()#查看所有记录
# print(res1)
# print(res2)
# print(res3)
# print(res4)
print(res5) #提交
conn.commit()
#关闭游标
cursor.close()
#关闭连接
conn.close()
''' ((1, 'egon', '123'), (2, 'hu', '123'), (3, 'root', '123456'), (4, 'lhf', '12356'), (5, 'eee', '156'))
'''
四 lastrowid获取最后一个自增id
前提:id必须是自动增长的,auto_increment
例子:
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='',database='user')
cursor=conn.cursor() sql="insert into t1(name,pwd) values('aaa','123')"
rows=cursor.execute(sql)
print(cursor.lastrowid) #在插入语句后查看 conn.commit() cursor.close()
conn.close()
最新文章
- CodeSmith7 系列 破解教程
- mybatis多对一关联
- 如何为datagridview加上序号
- myrocks记录格式分析
- mvc-6依赖管理
- android 资源ID
- idea破解码
- Eclipse将引用了第三方jar包的Java项目打包成jar文件
- 巨杉数据库加入CNCF云原生应用计算基金会,共建开源技术生态
- C 线性表的链式存储实现及插入、删除等操作示例
- Confluence 6 为空白空间编辑默认主页
- Intellij IDEA配置PHP开发环境
- rimraf 跨平台删除文件
- MVC设计模式在网站中的应用
- js 拷贝树copytree
- 8款不错的 CI/CD工具
- (转)真正的中国天气api接口xml,json(求加精) ...
- c# 终止线程
- css3 圣诞红包雨效果
- WCF身份验证二:基于消息安全模式的自定义身份验证