python mysql 常见的第三方库
mysql-connector、pymysql 这个两个的使用基本一致
pip install mysql.connector
pip show mysql.connector
import mysql.connector
# 创建连接
conn=mysql.connector.connect(host="数据库地址"
,port="3311"
,user="admin"
,password="123456"
,database="test"
,auth_plugin= "mysql_native_password")
# 获取游标
cur=conn.cursor()
# 插入
sql="insert into user(Name,Age) values(%s,%s)"
data=('zhang01',18)
cur.execute(sql,data)
# 批量插入
sql="insert into user(Name,Age) values(%s,%s)"
data=[('test01',18),("test02",12)]
cur.executemany(sql,data)
# 提交
conn.commit()
sql="select * from user"
# 查询所有
cur.execute(sql)
# 获取所有数据
data=cur.fetchall()
print(data)
cur.execute(sql)
# 获取最新10条数据
data=cur.fetchmany(10)
print(data)
# 获取字段
column_names=cur.column_names
print(column_names)
# 关闭
conn.close()
错误:mysql.connector.errors.NotSupportedError: Authentication plugin ‘caching_sha2_password’ is not supported
原因是在 MySQL 8.0 以后,默认的密码加密方式是 caching_sha2_password 而不是mysql_native_password
解决方案:
登录mysql 服务,创建一个新的账户,然后设置mysql_native_password
docker ps
docker exec -it 2a4533834734 /bin/bash
mysql -u root -p
#查看用户
select user,plugin from mysql.user;
#创建用户
create user '用户名'@'%' identified with mysql_native_password by '密码';
#设置权限
grant all privileges on *.* to '用户名'@'%' with grant option;
#刷新
flush privileges;
all privileges 表示将所有权限授予给用户,可指定具体的权限(SELECT、CREATE、DROP)
on:数据库名.表名,这里写*表示所有数据库,所有表,如果特定库名.表名
to:将权限授予哪个用户。格式:”用户名”@”登录IP或域名”。
% 表示没有限制,在任何主机都可以登录
identified by 指定用户的登录密码
with grant option:表示允许用户将自己的权限授权给其它用户
错误:mysql.connector.errors.InterfaceError: Use multi=True when executing multiple statements
原因:但是在8.0之后不再设置为默认同时执行多条sql语句,需要手动配置client_flag=CLIENT.MULTI_STATEMENTS
pip install pymysql
pip show pymysql
import pymysql
# 创建连接
conn=pymysql.connect(host="数据库地址"
,port=3311
,user="admin"
,password="123456"
,database="test"
)
# 获取游标
cur=conn.cursor()
# 插入
sql="insert into user(Name,Age) values(%s,%s)"
data=('pymysql01',18)
cur.execute(sql,data)