当前位置: 首页 > article >正文

python mysql pymysql 数据库操作,常用脚本,个人小工具

起因, 目的:

整理 mysql 工具

启动数据库

检查服务器是否启动了: Get-Service -Name ‘mysql*’
如果没启动的话,那么就启动:

net start MySQL80 (最好是开启管理员权限)

1, 日常最常用的,创建连接 --> 查看所有数据库 —> 查看所有的表
import pymysql.cursors

def get_connection():
    connection = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='root',
        database='gamelearning',  # 数据库名
        local_infile=True,  # 使用本地数据库文件
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection

def get_tables(connection):
    with connection.cursor() as cursor:
        cursor.execute("SHOW TABLES")
        tables = cursor.fetchall()
    return tables

# 获取数据库连接
connection = get_connection()

# 获取数据库中的所有表
tables = get_tables(connection)

# 打印所有表名
print(f"数据库: gamelearning 包含的全部的 tables:")
for table in tables:
    print(table)
    # print(table['Tables_in_gamelearning'])


print()
print()
print()
print("打印 student 中 全部的内容: ")

# 打印 student 中 全部的内容
def get_all_rows(connection, table_name):
    with connection.cursor() as cursor:
        cursor.execute(f"SELECT * FROM `{table_name}`")
        rows = cursor.fetchall()
    return rows


# 获取 student 表中的所有内容
student_rows = get_all_rows(connection, 'professor')

# 打印所有学生信息
for student in student_rows:
    print(student)

# 关闭数据库连接
connection.close()


2. 连接远程数据库
import pymysql.cursors # pip install pymysql

# Connect to the database
connection = pymysql.connect(host='124.xxx.yyy.158',
                             user='root',
                             password='123456',
                             database='mysql',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

with connection:
    with connection.cursor() as cursor:
        # 1. 查看全部数据库名称
        sql = "show databases"
        cursor.execute(sql)
        result = cursor.fetchall()
        print(result)
        print()
        # [{'Database': 'information_schema'}, {'Database': 'mysql'}, {'Database': 'performance_schema'}, {'Database': 'sys'}]

        # 3. 查看 某一个数据库,比如 mysql 的表名称
        sql2 = "show tables from mysql"
        cursor.execute(sql2)
        result2 = cursor.fetchall()
        print(result2)
        print()

        # 3. 查看全部表名称
        for d in result:
            sql3 = f"show tables from {d['Database']}"
            cursor.execute(sql3)
            result3 = cursor.fetchall()
            ret33 = f"{d['Database']} tables are: {result3}"
            print(ret33)
            print()

3. pymysql 写成类的形式:
import pymysql

# pymysql 常用的操作流程。其他项目也是经常用的。
# 这是一个模板文件,随时可以拿出来用,根据情况修改。

class DB:
    def __init__(self, db_name):
        # 创建连接。注意修改为自己的用户名和密码。
        self.conn = pymysql.connect(host='localhost', user='root', password='root', charset='utf8mb4')

        # 创建游标
        self.cur = self.conn.cursor()
        self.db_name = db_name

    def create_database(self):
        # 创建数据库的sql(如果数据库存在就不创建,防止异常)
        sql = f"CREATE DATABASE IF NOT EXISTS {self.db_name}"
        print(sql)
        # 执行创建数据库的sql
        self.cur.execute(sql)

    # 创建表
    def create_table(self):
        # 选择使用的数据库
        u = f'use {self.db_name};'
        self.cur.execute(u)

        # 判断 table 是否存在, 然后再创建,放在报错。
        sql = '''CREATE TABLE  IF NOT EXISTS `friends_info` (
          `id` INT NOT NULL AUTO_INCREMENT,
          `age` INT ,
          `name` varchar(20) unique not null,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        '''
        self.cur.execute(sql)

    # 添加数据。
    def add_data(self):
        # 选择使用的数据库
        u = f'use {self.db_name};'
        self.cur.execute(u)

        # 执行插入语句。
        sql = """insert into friends_info(id,age,name) values (3,24,'bill')"""
        self.cur.execute(sql)

        # 主要要提交
        self.conn.commit()
        self.conn.close()

    # 查看数据
    def show_data(self):
        # 选择使用的数据库
        u = f'use {self.db_name};'
        self.cur.execute(u)

        sql = 'select * from friends_info'
        self.cur.execute(sql)

        # 此时可以获取全部查到的数据
        results = self.cur.fetchall()
        for row in results:
            print(row)              # (2, 22, 'alllen')
            print(type(row))        # <class 'tuple'>



# 这里调用的时候,根据自己的需求来选择使用那个函数,然后把用不到的注释掉。
if __name__ == '__main__':
    database_name = "pad"
    db = DB(database_name)
    db.create_database()

    # db.create_table()
    # db.add_data()

    # db.show_data()

    print("ok")


"""
表:
create table `student` (
`id` int unsigned auto_increment primary key,
`name` varchar(20) unique not null,
`gender` enum('男', '女') not null,
`location` varchar(10) not null,
`birthday` date default '1995-01-01',
`chinese` float(4, 1) not null default 0,
`math` float(4, 1) not null default 0,
`english` float(4, 1) not null default 0,
`only_child` boolean
) charset='utf8mb4';


数据:
insert into student
    (`name`, `gender`, `location`, `birthday`, `chinese`, `math`, `english`, `only_child`)
values
('萧峰', '男', '北京', '2000-10-1', 93, 91, 94, true),
('阿朱', '女', '苏州', '1997-07-05', 67, 56, 69, false),
('虚竹', '男', '广州', '1996-9-9', 94, 86, 82, true),
('郭靖', '男', '深圳', '1995-4-4', 97.5, 94, 95, false),
('小昭', '女', '北京', '1996-08-10', 67, 56, 58, false),
('杨康', '男', '成都', '1998-10-5', 41, 75, 66, false),
('张无忌', '男', '西安', '1994-8-30', 62, 98, 55, true),
('多隆', '男', '上海', '1997-11-28', 67, 56, 24, false),
('王语嫣', '女', '青岛', '1997-07-25', 67, 56, 80, false),
('黄蓉', '女', '北京', '1999-10-01', 67, 56, 77, false),
('令狐冲', '男', '杭州', '1997-5-2', 85.0, 100.0, 70, false),
('郭襄', '女', '厦门', '1998-02-22', 67, 56, 70, false),
('小龙女', '女', '西安', '1995-09-20', 67, 56, 69, false),
('韦小宝', '男', '上海', '1995-6-1', 60, 46, 58, false),
('周芷若', '女', '重庆', '1997-10-12', 67, 56, 74, false),
('杨过', '男', '北京', '1996-7-9', 82, 59.5, 70, false),
('赵敏', '女', '上海', '1997-10-16', 67, 56, 73, false),
('双儿', '女', '南京', '1994-09-08', 67, 56, 50, false),
('沐剑屏', '女', '北京', '1998-09-19', 67, 56, 22, false),
('段誉', '男', '上海', '1995-3-2', 59.5, 59.5, 58, false);

"""

个人接单,python, R语言,有事请私聊

老哥,支持一下啊。

支付宝扫码领红包哦


http://www.kler.cn/news/316925.html

相关文章:

  • 通过 LabVIEW 正则表达式读取数值(整数或小数)
  • Java基础尚硅谷85-面向对象特征一:封装性
  • Java中的事件(动作监听-ActionListener)
  • 如何使用ssm实现企业文档管理系统+vue
  • OpenHarmony(鸿蒙南向开发)——小型系统内核(LiteOS-A)【Perf调测】
  • Tcping:一款实用的端口存活检测工具
  • spring自定义属性编辑器
  • 本地生活商城开发搭建 同城O2O线上线下推广
  • 为什么 Feign 要用 HTTP 而不是 RPC?
  • Dify创建自定义工具,调用ASP.NET Core WebAPI时的注意事项(出现错误:Reached maximum retries (3) for URL ...)
  • Java_Day03学习
  • 前端vue左侧树的一整套功能实现(一):vue2+vite封装v-resize指令,实现左侧树拖拽宽度和折叠展开
  • Java面向对象——内部类(成员内部类、静态内部类、局部内部类、匿名内部类,完整详解附有代码+案例)
  • 江协科技STM32学习- P14 示例程序(定时器定时中断和定时器外部时钟)
  • web基础—dvwa靶场(十一)CSP Bypass
  • Linux相关概念和重要知识点(6)(make、makefile、gdb)
  • SQLServer数据分页
  • Python 中的函数装饰器:理解 @property、Getter 和 Setter 方法
  • (算法)大数的进制转换
  • ESP32-WROOM-32 [创建AP站点-客户端-TCP透传]
  • PostgreSQL中的regexp_split_to_table函数详解,拆分字段为多行
  • C++之STL—vector容器进阶篇
  • C++ STL全面解析:六大核心组件之一----序列式容器(vector和List)(STL进阶学习)
  • H5网页嵌在APP内部 手机锁屏后再打开 setInterval会重复执行
  • 【Git原理与使用】版本管理与分支管理(1)
  • LIN总线CAPL函数—— 设置报头同步间隔场长度(linSetBreakLength)
  • Redis数据结构之list列表
  • 116页可编辑PPT全面了解数据治理体系、平台,数据质量数据标准
  • Algo-Lab 2 Stack Queue ADT
  • 重修设计模式-设计原则