python自动化笔记:操作mysql数据库

操作mysql数据库常见方法

1、第三方库:pymysql

1.1、安装pymysql

终端输入:pip install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple/

1.2、连接数据库

python 复制代码
import pymysql

def connect():
    # 连接数据库
    conn = pymysql.connect(
    host="localhost",
    user="root",
    password="123456"
    )
    print(conn)
    return(conn)
# 调用
connect()

1.3、连接指定数据库

python 复制代码
def connect_database(database):
    # 连接数据库
    conn = pymysql.connect(
    host="localhost",
    user="root",
    password="123456",
    database=database
    )
    print(conn)
    return(conn)

connect_database("test")

1.4 创建数据库、创建表

python 复制代码
# 创建数据库
def creatdatabase(databasename):
    # 连接数据库
    conn = pymysql.connect(
        host="localhost",
        user="root",
        password="123456"
    )
    # 创建游标对象
    cursor = conn.cursor()
    # sql中使用变量,格式化输出
    # 创建数据库
    sql ="CREATE DATABASE IF NOT EXISTS {0}".format(databasename)
    cursor.execute(sql)
    # 展示所有数据库
    cursor.execute("SHOW DATABASES;")
    # 展示执行结果
    for database in cursor:
        print(database)
# 调用
creatdatabase("test")

# 创建表
def createtable():
    conn = pymysql.connect(
        host="localhost",
        user="root",
        password="123456",
        database="test"
    )
    cursor = conn.cursor()
    # 删除表格
    cursor.execute("drop table if exists student")
    # 创建表格
    sql="create table student(id int auto_increment primary key, name varchar(20), class varchar(255))"
    cursor.execute(sql)

# 调用
createtable()

1.5、表中插入数据

python 复制代码
def insertdata():
    conn = pymysql.connect(
        host="localhost",
        user="root",
        password="123456",
        database="test"
    )
    # 创建游标对象
    cursor=conn.cursor()
    # 插入数据sql,2种方式,推荐使用第一种占位符的方式,避免sql注入
    # 方式一
    addsheshou_sql="insert into student(name,class)values(%s, %s)"
    addsheshou_value = ("luban", "1")
    cursor.execute(addsheshou_sql,addsheshou_value)
    # 方式二
    addfashi_sql = "insert into student(name,class)values('anqila','2')"
    cursor.execute(addfashi_sql)
    # 提交
    conn.commit()
    # 查询语句
    cursor.execute("select * from student where name='luban' ")
    # 查看返回结果
    res = cursor.fetchall()
    print(res)

# 调用
insertdata()

查看数据库增加了2条数据(也可通过命令行窗口查看):

1.6、批量插入数据

python 复制代码
def insertmany(database):
    conn = connect_database(database)
    # 创建游标对象
    cursor=conn.cursor()
    # 插入数据sql
    addmany_sql="insert into student(name,class)values(%s, %s)"
    addmany_values = (("huangzhong", "1"),("direnjie", "1"),("zhenji", "2"),("zhongwuyan", "3"))
    cursor.executemany(addmany_sql,addmany_values)
    # 提交
    conn.commit()
    select_showall(database, "select * from student")

insertmany('test')

查看数据库增加了多条数据(也可通过命令行窗口查看):

1.7、获取查询结果数据

常用方法:

fetchall() 获取所有的记录

fetchone()获取第一行记录

fetchmany(size)获取前几行记录

python 复制代码
def select_showall(database,sql):
    conn=connect_database(database)
    # 创建游标对象
    cursor = conn.cursor()
    cursor.execute(sql)
   
    # 每次执行cur.fetchone()语句,游标都会向下走,所以不能同时查询
    # 查询所有记录
    # allrows = cursor.fetchall()
    # print(allrows)
    # 查询多条记录
    # manyrows = cursor.fetchmany(2)
    # print(manyrows)
    # 查询第一条数据
    onerow = cursor.fetchone()
    print(onerow)
    print(type(onerow))

# 调用
select_showall('test','select * from student where class="1"')

1.8、防sql注入,sql语句中一般用占位符传值

python 复制代码
def select_data(database):
    conn=connect_database(database)
    # 创建游标对象
    cursor = conn.cursor()
    # 避免sql注入
    sql="select * from student where name=%s"
    svalue=("luban",)
    data=cursor.execute(sql,svalue)
    print(data)

select_data('test')

2、标准库 :mysql.connector

2.1、安装mysql-connector

终端输入:pip install mysql-connector -i https://pypi.tuna.tsinghua.edu.cn/simple/

2.2、操作方法

实现的逻辑跟pysql一致,相同的操作,操作方法也一致

相关推荐
子墨77727 分钟前
Flask之Hello world 详解
python
繁依Fanyi29 分钟前
旅游心动盲盒:开启个性化旅行新体验
java·服务器·python·算法·eclipse·tomcat·旅游
计算机编程-吉哥34 分钟前
计算机毕业设计 基于Python的个性化旅游线路推荐系统的设计与实现 Python+Django+Vue 前后端分离 附源码 讲解 文档
python·django·毕业设计·课程设计·毕业论文·计算机毕业设计选题·个性化旅游线路推荐系统
罔闻_spider39 分钟前
爬虫prc技术----小红书爬取解决xs
爬虫·python·算法·机器学习·自然语言处理·中文分词
python机器学习ML43 分钟前
机器学习K近邻算法——python详细代码解析(sklearn)(1)
python·机器学习·近邻算法·knn
大拇指的约定1 小时前
数据库(MySQL):使用命令从零开始在Navicat创建一个数据库及其数据表(三),单表查询
数据库·mysql·oracle
DanCheng-studio1 小时前
毕设 大数据抖音短视频数据分析与可视化(源码)
python·毕业设计·毕设
阳光阿盖尔1 小时前
redis——哨兵机制
数据库·redis·缓存·主从复制·哨兵
小小娥子1 小时前
【Redis】Hash类型的常用命令
数据库·spring boot·redis
盒马盒马1 小时前
Redis:cpp.redis++通用接口
数据库·c++·redis