PyMySql介绍

pip install pymysql

PyMySql处理数据库增删改查

说明:以下代码都是python3.8版本,表结构是id、name、age,其中id设置为自动增长

#实现mysql数据库操作的步骤:增
import pymysql
#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

"""
str_sql1 = "CREATE TABLE `7test` (\
  `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,\
  `sex` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,\
  PRIMARY KEY (`name`,`sex`) USING BTREE\
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC;"
get_cursor.execute(str_sql1)
"""

#3.定义sql语句:
str_sql = "INSERT INTO 7test(name, age) VALUES (%s, %s);"
username = "wood"
age = 20

#4.通过游标:执行sql语句
get_cursor.execute(str_sql, [username, age])

#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()

#6.将数据库对象进行关闭
get_conn.close()

执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_mysql

插入数据失败回滚

#实现mysql数据库操作的步骤:插入数据失败回滚
import pymysql

#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

#3.定义sql语句:
str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"
username = "wood_test"
age = 29

#4.通过游标:执行sql语句
try:
    # 执行SQL语句
    get_cursor.execute(str_sql, [username, age])
    #再执行一个sql语句,错误的sql语句
    get_cursor.execute(str_sql,username)
    # 提交事务
    get_conn.commit()
except Exception as e:
    # 有异常,回滚事务
    get_conn.rollback()
    print("抛出异常,事务回滚")

#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()

#6.将数据库对象进行关闭
get_conn.close()

执行结果如下:数据库中数据不插入第一条数据

python高阶学习笔记:7 python操作Mysql数据库_sql语句_02


获取插入数据的ID(关联操作时会用到)

#-*- coding:utf-8 -*-#
#-------------------------------------------------------------------------
#ProjectName:       Python2020
#FileName:          MysqlTest.py
#Author:            mutou
#Date:              2020/5/31 18:44
#Description:对mysql进行数据库操作
#--------------------------------------------------------------------------
#实现mysql数据库操作的步骤:
import pymysql
#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_cnotallow=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")
#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()
#3.定义sql语句:
str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"
username = "wood_id"
age = 22
#4.通过游标:执行sql语句
try:
    # 执行SQL语句
    get_cursor.execute(str_sql, [username, age])
    # 提交事务
    get_conn.commit()
    # 提交之后,获取刚插入的数据的ID
    last_id = get_cursor.lastrowid
    print("最后一条数据的ID是:", last_id)
except Exception as e:
    # 有异常,回滚事务
    get_conn.rollback()
    print("事务回滚,出现异常")
#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()
#6.将数据库对象进行关闭
get_conn.close()


python高阶学习笔记:7 python操作Mysql数据库_mysql_03

python高阶学习笔记:7 python操作Mysql数据库_sql_04

批量执行

#实现mysql数据库操作的步骤:
import pymysql
#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_cnotallow=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")
#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()
#3.定义sql语句:
str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"
data = [("Tom", 18), ("Jack", 20), ("Jerry", 22)]
#4.通过游标:执行sql语句
try:
    # 批量执行多条插入SQL语句
    get_cursor.executemany(str_sql, data)
    # 提交事务
    get_conn.commit()
except Exception as e:
    # 有异常,回滚事务
    get_conn.rollback()
    print("事务回滚")
#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()
#6.将数据库对象进行关闭
get_conn.close()

执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_sql语句_05

#实现mysql数据库操作的步骤:删
import pymysql
#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

#3.定义sql语句:
str_sql = "DELETE FROM 7test WHERE name=%s;"

#4.通过游标:执行sql语句
try:
    # 批量执行多条插入SQL语句
    get_cursor.execute(str_sql, "Tom")
    # 提交事务
    get_conn.commit()
except Exception as e:
    get_conn.rollback()
    print("事务回滚")

#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()

#6.将数据库对象进行关闭
get_conn.close()


执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_sql语句_06

#实现mysql数据库操作的步骤:修改
import pymysql

#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

#3.定义sql语句:
str_sql = "UPDATE 7test SET age=%s WHERE name=%s;"
username = "Jack"
age = 77

#4.通过游标:执行sql语句
try:
    # 批量执行多条插入SQL语句
    get_cursor.execute(str_sql, [age,username])
    # 提交事务
    get_conn.commit()
except Exception as e:
    # 有异常,回滚事务
    get_conn.rollback()
    print("事务回滚")

#5.事务:针对修改、删除、增加是需要操作事务,即事务提交
get_conn.commit()

#6.将数据库对象进行关闭
get_conn.close()

执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_sql语句_07

#实现mysql数据库操作的步骤:查找
import pymysql
#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

#3.定义sql语句:
sql = "select * from 7test"
try:
    get_cursor.execute(sql)  # 执行sql语句
    results = get_cursor.fetchall()  # 获取查询的所有记录
    print("name", "password")
    # 遍历结果
    for row in results:
        name = row[0]
        password = row[1]
        print(name, password)
except Exception as e:
    raise e
finally:
    get_conn.close()  # 关闭连接

执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_sql_08


查询单条数据

#实现mysql数据库操作的步骤:查找单条
import pymysql

#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名
get_conn=pymysql.connect(host="127.0.0.1",user="root",password="password",database="testdb")

#2.需要获取游标,用于执行sql语句并存储结果集
get_cursor=get_conn.cursor()

#3.定义sql语句:
sql = "select * from 7test where name=%s";
username = "wood"

# 4.获取单条查询数据
get_cursor.execute(sql,username)
ret = get_cursor.fetchone()
get_cursor.close()
get_conn.close()
# 打印下查询结果
print(ret)

执行结果如下:

python高阶学习笔记:7 python操作Mysql数据库_sql_09


数据库中插入一万条数据

项目结构:

python高阶学习笔记:7 python操作Mysql数据库_sql语句_10

其中造数据模块Create_Data:

#-*- coding:utf-8 -*-#
#-------------------------------------------------------------------------
#ProjectName:       Python2020
#FileName:          Create_Data.py
#Author:            mutou
#Date:              2020/6/2 21:00
#Description:造数据:要求:姓名必须是6-12位,性别随机、年龄18-100之间随机;
#数据的条件:可以通过python 程序直接判定,同样的可以联想到数据库做数据检查
#--------------------------------------------------------------------------
import random
import string
class CreateData(object):
    #造一万条:姓名随机造数据要求6-12位
    #可以从数字、字母、符号等进行随机取值;还可以从网络上获取一些文字,数据进行筛选;
    #python自带有一个string模块,该模块可以获取对应的所有字符串
    def  get_name(self):
        str_char=""
        #随机选值的容器:数字、大小写、符号
        get_char=string.ascii_letters+string.digits   #+string.punctuation
        #定义随机的6-12位的数字
        get_len=random.randint(6,12)
        for i in range(1,get_len+1):
            str_char+=random.choice(get_char)
        return str_char
    #性别的操作
    def get_sex(self):
        return random.choice(["男","女"])


    #年龄的数据
    def  get_age(self):
        return random.randint(18,100)


    #声明一个方法进行,一条数据将其放在一个列表
    def  get_one_data(self):
        #此处返回的数据顺序最好与创建表时结构顺序一致,便于插入数据时一一对象
        return [self.get_name(),self.get_sex(),self.get_age()]


if __name__=="__main__":
    #测试代码
    create=CreateData()
    print(create.get_name())
    print(create.get_one_data())

数据库插入数据模块:

#-*- coding:utf-8 -*-#
#-------------------------------------------------------------------------
#ProjectName:       Python2020
#FileName:          Conn_Mysql.py
#Author:            mutou
#Date:              2020/6/2 21:15
#Description:连接mysql数据库,完成数据插入操作
#--------------------------------------------------------------------------
import pymysql
from Day14.Data_Opera.Create_Data import CreateData
class ConnMysql(object):
    #获取数据库连接:
    def __init__(self):
        self.get_cnotallow=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")
        #创建游标
        self.get_cursor=self.get_conn.cursor()


    #定义sql语句并通过游标执行
    def create_table(self,tablename):
        #定义创建表的sql语句,其实此处可以将字段全部设置为不定长参数
        str_sql="create table %s(student_id int,student_name varchar(20),student_sex char(4),student_age int);"%(tablename)
        #通过游标进行执行sql语句
        self.get_cursor.execute(str_sql)




    #定义插入数据的
    def insert_data(self,tablename,*args):
        #此处需要考虑如何插入,插入数据的可以定义四个参数,也可以定义不定长
        #此处考虑引号、转义符;如果姓名存在转义符或者引号的话则需要在此添加转义符
        #str_sql="insert into %s values(%s,'%s','%s',%s)"%(tablename)
        str_sql = "insert into student_test values(%s,%s,%s,%s);"
       # print(str_sql)
        #self.get_cursor.execute(str_sql)
        print(str_sql)
        #讲执行效率
        self.get_cursor.executemany(str_sql,args)
        #测试出一个参数的情况
        #self.get_cursor.executemany("insert into student values(%s)",args)
        #等价的是for argv in args:
        #self.get_cursor.execute("insert into student values(%s)",argv)
        self.get_conn.commit()
    #定义一个关闭对象的方法
    def close_conn(self):
        self.get_conn.close()


#测试代码:以后的测试代码都会定义在main方法中
#__name__在当前模块其值就是main
if __name__=="__main__":
    cnotallow=ConnMysql()
    createdata=CreateData()
    #conn.create_table("student_test")
    #插入一万条数据
    #获取一组数据
    list1=[]
    for i in range(1,10001):
        get_notallow=createdata.get_one_data()
        get_one.insert(0,i)
        list1.append(get_one)
    conn.insert_data("student_test",*list1)
    #conn.insert_data(*[i for i in range(1,100)])
    conn.close_conn()