一 安装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()

最新文章

  1. CodeSmith7 系列 破解教程
  2. mybatis多对一关联
  3. 如何为datagridview加上序号
  4. myrocks记录格式分析
  5. mvc-6依赖管理
  6. android 资源ID
  7. idea破解码
  8. Eclipse将引用了第三方jar包的Java项目打包成jar文件
  9. 巨杉数据库加入CNCF云原生应用计算基金会,共建开源技术生态
  10. C 线性表的链式存储实现及插入、删除等操作示例
  11. Confluence 6 为空白空间编辑默认主页
  12. Intellij IDEA配置PHP开发环境
  13. rimraf 跨平台删除文件
  14. MVC设计模式在网站中的应用
  15. js 拷贝树copytree
  16. 8款不错的 CI/CD工具
  17. (转)真正的中国天气api接口xml,json(求加精) ...
  18. c# 终止线程
  19. css3 圣诞红包雨效果
  20. WCF身份验证二:基于消息安全模式的自定义身份验证

热门文章

  1. Git的基本了解与使用、向github提交代码
  2. ubuntu忘记root密码
  3. R330 打印机连供墨水红灯常量处理
  4. JS文字翻滚效果
  5. C++: Mac上安装Boost库并使用CLion开发
  6. 【P3056】【USACO12NOV】笨牛Clumsy Cows
  7. Laravel(PHP)使用Swagger生成API文档不完全指南 - 基本概念和环境搭建 - 简书
  8. ML面试1000题系列(61-70)
  9. js的各种获取大小
  10. unity如何查找某个脚本挂在了哪些物体上