pymysql 数据库链接
如果没有安装 PyMySQL ,参考安装文档。
PyMySQL 安装文档
前期建库准备
create user citizenwang identified by 'yourpassword';
create database python;
grant all privileges on *.* to 'citizenwang'@'%' identified by 'yourpassword';
blush privileges;
连接数据库 connect
connet 方法返回一个数据库链接对象 <class 'pymysql.connections.Connection'>
方法1:直接使用 connect 方法
connection = pymysql.connect(host='localhost', port=3306, user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
- charset 字符集,一般是 utf8
- port 端口, 默认 3306
cursorclass 建议省略
方法2:使用字典 或 函数连接数据库
def connect_mysql():
db_config = {
'host':'127.0.0.1',
'port':3306,
'user':'db_user',
'password':'db_user_passwd',
'db':'database_name',
'charset':'utf8mb4'
}
try:
cms = pymysql.connect(**db_config)