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

embedded/2024/9/24 0:49:45/

起因, 目的:

整理 mysql 工具

启动数据库

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

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

1, 日常最常用的,创建连接 --> 查看所有数据库 —> 查看所有的表
python">import pymysql.cursorsdef 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 connectiondef 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()
mysql___113">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_namedef create_database(self):# 创建数据库的sql(如果数据库存在就不创建,防止异常)sql = f"CREATE DATABASE IF NOT EXISTS {self.db_name}"print(sql)# 执行创建数据库的sqlself.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_240">个人接单,python, R语言,有事请私聊

老哥,支持一下啊。

支付宝扫码领红包哦


http://www.ppmy.cn/embedded/115824.html

相关文章

Kotlin高阶函数func

Kotlin高阶函数func fun sum(a: Int, b: Int, someFunc: () -> Unit) {println("${a b}")someFunc() }fun myFunc() {println("计算成功") }fun main() {sum(1, 2, ::myFunc) } 输出&#xff1a; 3 计算成功 Kotlin函数作为参数指向不同逻辑_ketlin 将…

即插即用!高德西交的PriorDrive:统一的矢量先验地图编码,辅助无图自动驾驶

Driving with Prior Maps: Unified Vector Prior Encoding for Autonomous Vehicle Mapping 论文主页&#xff1a;https://misstl.github.io/PriorDrive.github.io/ 论文链接&#xff1a;https://arxiv.org/pdf/2409.05352 代码链接&#xff1a;https://github.com/missTL/Pr…

Llamaindex 使用过程中的常见问题 (FAQ)

导读 在使用LlamaIndex进行文档索引和查询时&#xff0c;您可能会发现需要根据特定的需求对基础设置进行调整。下面是一些常见的定制化需求及其对应的实现方式&#xff1a; 文档分割&#xff1a;为了更好地管理和查询大型文档&#xff0c;您可以选择将文档分割成更小的块。这可…

华为HarmonyOS地图服务 1 -- 如何实现地图呈现?

如何使用地图组件MapComponent和MapComponentController呈现地图&#xff0c;效果如下图所示。 MapComponent是地图组件&#xff0c;用于在您的页面中放置地图。MapComponentController是地图组件的主要功能入口类&#xff0c;用来操作地图&#xff0c;与地图有关的所有方法从此…

基于STM32的温度、电流、电压检测proteus仿真系统(OLED、DHT11、继电器、电机)

目录 一、主要功能 二、硬件资源 三、程序编程 四、实现现象 一、主要功能 基于STM32F103C8T6 采用DHT11读取温度、滑动变阻器模拟读取电流、电压。 通过OLED屏幕显示,设置电流阈值为80,电流小阈值为50,电压阈值为60,温度阈值为30 随便哪个超过预祝,则继电器切断,LE…

Android14请求动态申请存储权限

Android14请求动态申请存储权限 Android14和Android15存储权限有增加多了选择部分&#xff0c;还是全部。一个小小的存储权限真的被它玩出了花来。本来Android13就将存储权限进行了3个细分&#xff0c;是图片&#xff0c;音频还是视频文件。 步骤一&#xff1a;AndroidManife…

webservice cxf框架 jaxrs jaxws spring整合 接口测试方法 wsdl报文详解 springboot整合 拦截器 复杂参数类型

webservice cxf框架 jaxrs jaxws spring整合 【java进阶教程之webservice深入浅出【黑马程序员】】 webservice接口测试方法 【SoapUI让你轻松玩转WebService接口测试【特斯汀学院】】 webservice wsdl报文详解 【webservice - 尚硅谷周阳新视频】 webservice springbo…

代码随想录算法训练营Day8 | 344.反转字符串、541.反转字符串Ⅱ、替换数字

344.反转字符串 题目 344. 反转字符串 - 力扣&#xff08;LeetCode&#xff09; 编写一个函数&#xff0c;其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。 不要给另外的数组分配额外的空间&#xff0c;你必须原地修改输入数组、使用 O(1) 的额外空间…