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

起因, 目的:

整理 mysql 工具

启动数据库

检查服务器是否启动了: Get-Service -Name 'mysql*'

如果没启动的话,那么就启动:

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

1, 日常最常用的,创建连接 --> 查看所有数据库 ---> 查看所有的表
python 复制代码
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. 连接远程数据库
python 复制代码
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 写成类的形式:
python 复制代码
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语言,有事请私聊

老哥,支持一下啊。

相关推荐
chusheng184041 分钟前
Python 中的 Socket 编程入门
开发语言·网络·python
Sean X1 小时前
yolov5测试代码
python·yolo
bandaoyu2 小时前
【RDMA】mlxconfig修改和查询网卡(固件)配置--驱动工具
服务器·网络·数据库
梦茹^_^2 小时前
EC Shop安装指南 [ Apache PHP Mysql ]
数据库·测试工具·mysql·php·apache·httpd·ec shop
codelife3212 小时前
设计模式——对象池模式
数据库·设计模式·oracle
YOLO数据集工作室2 小时前
Python人工智能学习路线
人工智能·python·学习
橙子小哥的代码世界3 小时前
深度学习02-pytorch-02-张量的拼接操作
人工智能·pytorch·python
yunson_Liu3 小时前
编写Python脚本在证书过期10天内将域名信息发送到钉钉
开发语言·python·钉钉
JAMES费3 小时前
python机器人编程——用手机web远程视频监控并控制小车驾驶(上篇vrep仿真)
python·智能手机·机器人