Python之MYSQL数据库基础操作
一、基本介绍
1.驱动程序
Python要想操作MYSQL,必须要有一个中间件(驱动程序),如:1.mysqldb(只在python2中有用)
2.mysqlclient
3.pymysql
这里以pymysql为例,安装方式可通过pip命令安装:pip install pymysql
2.DBeaver
(1)关于DBeaver
- DBeaver是一款操作数据库非常方便的软件(能够支持非常多非常丰富的数据库),使用它操作数据库跟使用Excel操作数据是一样的
- 它支持 Windows、Linux 和 macOS系统
- DBeaver 是由 Java 编写的,默认使用 JDK 11 进行编译。
(2)安装
可通过官网下载:https://dbeaver.io/download/
(3)配置镜像和建立连接
安装完成之后我们需要配置Maven镜像,这里提供阿里云镜像地址:http://maven.aliyun.com/nexus/content/groups/public
配置的方式为:窗口➡首选项➡输入框输入Maven➡添加镜像并置顶
配置镜像之后我们就可以连接数据库了,连接方式:
然后填写数据库连接信息
填写之后先点击测试连接,测试没问题之后就可以正式建立连接了
(4)连接可能出现失败的原因及解决方法
- 测试连接时,可能出现以下情况:null, message from server: “Host ‘xxxx‘ is not allowed to connect to this MySQL server“
- 原因是MYSQL没有开放远程登录操作的权限,我们需要对其进行修改
- 解决:
打开mysql数据库
1.先登录账号
2.输入use mysql;
3.输入select host, user from user; (查看user表中,连接权限,默认看到root是localhost)
4.输入update user set host = ‘%’ where user = ‘root’; (修改权限,将localhost修改为%)
5.执行FLUSH PRIVILEGES;(进行刷新)
二、数据库基础操作
1.数据库连接操作
- host:服务器的ip地址
- port:端口号(在外网一般会更换端口号,不会为3306,这是为了安全考虑)
- user:连接的用户(一般在生产环境中会单独分配一个账号给你,而不是使用root用户)
- password:用户密码
- database:连接操作的数据库名
- charest:一般设置为utf8,这样就可以操作中文
import pymysql
# 使用pymysql.connet方法连接数据库
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
# 建立游标,用于操作数据库
cursor = db.cursor()
# 使用cursor.execute来执行sql语句
cursor.execute("select * from biao1")
result = cursor.fetchone()
print(result)
db.commit() # 提交
db.close() #关闭
2.数据库插入操作
- 语法:insert into [表名(字段)] values(字段对应的值)
- 如果值是动态的,可以使用%s来替代,后期在使用execute方法的时候,可以用一个元组把这些数据填进去
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
cursor = db.cursor()
sql = "insert into biao1(id,name) values('2','杨开')"
cursor.execute(sql)
sql2 = "insert into biao1(id,name) values(%s,%s)"
cursor.execute(sql2, ('004', '苏颜'))
db.commit()
db.close()
3.数据库查找操作
- fetchone:提取第一条数据
- fetchall:提取select语句获取到的所有数据
- fetchmany:提取指定条数的数据
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
cursor = db.cursor()
sql = "select name from biao1"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
result2 = cursor.fetchall()
print(result2)
result3 = cursor.fetchmany(3)
print(result3)
sql = "select id from biao1 where id>2"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
db.commit()
db.close()
4.数据库删除操作
- 语法:delete from [表名] [条件]
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
cursor = db.cursor()
sql = "delete from biao1 where id=002"
cursor.execute(sql)
db.commit()
db.close()
5.数据库更新操作
- 语法:update [表名] [更新操作] [条件]
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123", charset="utf8mb4")
cursor = db.cursor()
# update 表名 更新操作 条件
sql = "update biao1 set name='伏天' where id=003"
cursor.execute(sql)
db.commit()
db.close()