python mysql 数据库

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)

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值