Python MySQL - mysql-connector 驱动

报错

1
Host 'xxx' is not allowed to connect to this MariaDB server

解决方案

1
grant all privileges on *.* to 'root'@'%' identified by 'password' with grant option;

注意

**意:**如果你的 MySQL 是 8.0 版本,密码插件验证方式发生了变化,早期版本为 mysql_native_password,8.0 版本为 caching_sha2_password,所以需要做些改变:

[mysqld]

user=mysql

validate_password.policy=LOW

default_authentication_plugin=mysql_native_password

1
2
# 或者
ALTER USER 'root'@'可访问root的主机' IDENTIFIED WITH mysql_native_password BY 'root的密码';

创建数据库链接

1
2
3
4
5
6
7
8
import mysql.connector as mysqlc
mydb=mysqlc.connect(
host=" ",
user=" ",
passwd=" ",
)
mycursor = mydb.cursor()
mycursor.execute("")

创建数据库

1
2
3
#创建数据库test_db
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE test_db")

使用execute()执行sql语句

关闭数据库链接

1
mydb.close()

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

  • fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  • fetchall(): 接收全部的返回结果行.
  • rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。