1. 安装PyMySQL

PyMySQL是从Python连接到MySQL数据库服务器的接口
使用命令行pip install PyMySQL进行安装

2. 创建数据库和表

(2.1)创建数据库

#创建数据库
import pymysql

#创建连接,使用pymysql从Python连接到mysql服务器
conn=pymysql.connect(host='localhost',port=3306,user='root',password='123456',charset='utf8mb4')
try:
    with conn.cursor() as cur:
        # 创建数据库db_name的sql,如果数据库存在则不创建
        sql = 'CREATE DATABASE IF NOT EXISTS db_name'
        # 执行创建数据库的sql
        cur.execute(sql)
finally:
    conn.close()

(2.2)创建表

import pymysql

#Python连接到数据库db_name
db=pymysql.connect(host='localhost',user='root',password='123456',db='db_name')
try:
    with db.cursor() as cur: #创建游标对象
        # 创建表table_name的sql
        sql="""CREATE TABLE table_name(
                id INT(11) NOT NULL AUTO_INCREMENT,
                email VARCHAR(255) COLLATE utf8_bin NOT NULL,
                password VARCHAR(255) COLLATE utf8_bin NOT NULL,
                PRIMARY KEY(id))
                """
        # 执行创建表的sql
        cur.execute(sql)
finally:
    db.close()

3. 插入与查询

import pymysql

#Python连接到数据库db_name
conn=pymysql.connect(host='localhost',user='root',password='123456',db='db_name')
try:
    with conn.cursor() as cur:
        # 向表table_name插入一条新记录的sql
        sql="INSERT INTO table_name (email,password) VALUES (%s,%s)"
        #执行sql
        cur.execute(sql,('123456789@qq.com','123456'))
        #提交更新数据的操作
        conn.commit()

    with conn.cursor() as cur:
        # 从表table_name查询记录的sql
        sql="SELECT id,password FROM table_name WHERE email=%s"
        #执行sql
        cur.execute(sql,('123456789@qq.com'))
        #获取下一行匹配的数据
        result=cur.fetchone()
        print(result)
finally:
    conn.close()

4. 操作过程分析

step1:连接数据库

connect=pymysql.connect(*args,**kwargs)

关键参数:
host:数据库服务器主机
user:登录数据库服务器的用户名称
password:登录数据库服务器的用户密码
database/db:操作的数据库名称
port:数据库使用的端口号,默认是3306
charset:使用的编码

step2:获取游标

直接操作数据库、直接执行sql语句的,是一个游标对象cursor

cursor=connect.cursor()

cursor执行完sql语句后,需要关闭,cursor.close()
在本示例中,使用了with…as…上下文,就不需要自行关闭游标

step3:执行sql语句

用的是cursor对象的方法

cursor.execute(sql,query,args=None)#执行一个sql语句
cursor.fetchone(self)#获取下一行匹配数据
cursor.fetchmany(self,size=None)#获取多行匹配数据
cursor.fetchall(self)#获取所有匹配数据

step4:提交更新数据的操作

所有有关更新数据的操作(insert、update、delete)都需要提交

connect.commit()

step5:回滚

如果提交有异常的话,可以进行回滚

connect.rollback()

step6:关闭数据库连接

connect.close()

示例

try:
	#执行sql语句
	cursor.execute(sql)
	#提交执行
	connect.execute()
except Exception as e:
	#如果执行sql语句出现异常,则执行回滚操作
	connect.rollback()
finally:
	#关闭游标和数据库连接
	cursor.close()
	connect.close()