pymysql的基本操作

1、Python3连接MySQL

1
2
3
import pymysql
 
pymysql.connect(host='localhost',user='root',password='1',database='demo_db',port=3306)

  

2、Python3操作MySQL

(1)查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pymysql
 
#连接MySQL
db = pymysql.connect('localhost','root','1','demo_db')
 
#获取游标
cursor = db.cursor()
 
#查询数据的SQL语句
sql = "select * from demo_tb;"
 
#执行SQL语句
cursor.execute(sql)
 
#获取查询的结果
res = cursor.fetchall()
 
#打印结果
print(res)
 
#结果为两条数据记录如下:
#(('alvin', 21, 'game'), ('rain', 24, 'ball'))

  

(2)插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
import pymysql
 
con = pymysql.connect(host='localhost',user='root',password='1',database='demo_db',port=3306)
cursor = con.cursor()
 
#插入的SQL语句
sql = "insert into demo_tb(name,age,hobby) values('tom',19,'football')"
 
#执行SQL,没有写入数据库
cursor.execute(sql)
 
#提交,此时才会真正写入数据库
con.commit()

  

(3)修改数据

1
2
3
4
5
6
7
8
9
10
11
12
13
import pymysql
 
con = pymysql.connect(host='localhost',user='root',password='1',database='demo_db',port=3306)
cursor = con.cursor()
 
#修改数据的SQL语句
sql = "update demo_tb set name='new_name' where hobby='ball'"
 
#执行SQL
cursor.execute(sql)
 
#提交修改,写入到数据库
con.commit()

  

(4)删除数据

1
2
3
4
5
6
7
8
9
10
11
12
13
import pymysql
 
con = pymysql.connect(host='localhost',user='root',password='1',database='demo_db',port=3306)
cursor = con.cursor()
 
#SQL语句
sql = "delete from demo_tb where name='tom'"
 
#执行SQL
cursor.execute(sql)
 
#提交,从数据库删除数据
con.commit()

  

 (5)关闭游标和关闭数据库连接

  调用close方法,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pymysql
 
user = input("username:")
pwd = input("password:")
 
conn = pymysql.connect(host="localhost",user='root',password='',database="db666")
cursor = conn.cursor()
sql = "select * from userinfo where username=%s and password=%s"
cursor.execute(sql,user,pwd)
# cursor.execute(sql,[user,pwd])
# cursor.execute(sql,{'u':user,'p':pwd})
result = cursor.fetchone()
cursor.close()
conn.close()
if result:
    print('登录成功')
else:
    print('登录失败')

  

posted @   映辉  阅读(89)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示