首页 > 数据库 >Python连接MySQL数据库

Python连接MySQL数据库

时间:2024-08-20 18:49:06浏览次数:11  
标签:Python 数据库 sql cursor -- file MySQL query

连接Mysql数据库

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb

# 连接数据库
db = MySQLdb.connect(host="localhost", user="zabbix", passwd="123123", db="zabbix")

# 创建cursor对象
cursor = db.cursor()

# 执行SQL查询
cursor.execute("SELECT VERSION()")

# 获取查询结果
data = cursor.fetchone()
print("Database version : %s " % data)

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

 

连接Mysql数据库并在脚本中调用SQL文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb

# 数据库连接参数
config = {
'host': 'localhost',
'user': 'zabbix',
'passwd': '123123',
'db': 'zabbix'
}

# 创建数据库连接
conn = MySQLdb.connect(**config)
cursor = conn.cursor()

# 读取并执行SQL文件
with open('insert.sql', 'r') as sql_file:
sql_script = sql_file.read()

# 执行SQL脚本
for statement in sql_script.split(';'):
if statement.strip():
cursor.execute(statement)

# 提交事务
conn.commit()

# 关闭连接
cursor.close()
conn.close()

在Python脚本中实现对MySQL的备份

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time

# 数据库连接信息
HOST = "localhost"
USER = "zabbix"
PASSWORD = "123123"
DB = "zabbix"

# 备份文件名(包含时间戳)
backup_file = "/root/zabbix_backup_" + time.strftime("%Y%m%d%H%M%S") + ".sql"

# 构建 mysqldump 命令
mysqldump_cmd = (
    'mysqldump -h {host} -u {user} -p{password} {db} > "{backup_file}"'
).format(
    host=HOST,
    user=USER,
    password=PASSWORD,
    db=DB,
    backup_file=backup_file
)

try:
    # 执行 mysqldump 命令
    os.system(mysqldump_cmd)
    print("backup successful:", backup_file)
except Exception as e:
    print("error:", e)

 在Python脚本中查询MySQL状态信息并输出结果集

监控数据库的查询SQL脚本可以写进Monitor.sql 如下

-- Server Version
SELECT VERSION();

-- Database Size
SELECT table_schema AS 'Database',
       ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)'
FROM information_schema.TABLES
GROUP BY table_schema
ORDER BY 'Size (MB)' DESC;

-- Table Status
SHOW TABLE STATUS;

-- InnoDB Status
SHOW ENGINE INNODB STATUS;

-- Connection Status
SHOW STATUS LIKE 'Threads_connected';

-- Query Status
SHOW STATUS LIKE 'Queries';

-- Lock Status
SHOW STATUS LIKE 'Innodb_row_lock_waits';

-- Cache Hit Rate
SHOW STATUS LIKE 'Qcache_hits';
SHOW STATUS LIKE 'Qcache_inserts';
SHOW STATUS LIKE 'Qcache_lowmem_prunes';

-- Error Log Location
SHOW VARIABLES LIKE 'log_error';

接下来,更 Python 脚本以读取和执行 .sql 文件中的查询

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb

# 数据库连接参数
HOST = "localhost"
USER = "zabbix"
PASSWORD = "123123"
DB = "zabbix"

# 输出文件路径
OUTPUT_FILE = "/root/mysql_status.txt"
SQL_FILE = "/root/monitor.sql"

def read_sql_file(file_path):
    """读取 SQL 文件内容"""
    with open(file_path, 'r') as file:
        return file.read()

def execute_query(cursor, query, f):
    """执行查询并将结果写入文件"""
    try:
        cursor.execute(query)
        while True:
            results = cursor.fetchall()
            if not results:
                break
            for row in results:
                f.write(str(row) + "\n")
            f.write("\n")
    except MySQLdb.Error as e:
        f.write("Error: %s\n" % e)
        f.write("\n")
    finally:
        # Ensure all results are fetched and cleared
        cursor.nextset()

def query_mysql_status():
    # 连接到 MySQL 数据库
    conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD, db=DB)
    cursor = conn.cursor()

    # 读取 SQL 文件
    sql_content = read_sql_file(SQL_FILE)
    queries = sql_content.split(';')

    with open(OUTPUT_FILE, 'w') as f:
        for query in queries:
            query = query.strip()
            if query:
                f.write("Executing query:\n" + query + "\n")
                execute_query(cursor, query, f)

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

if __name__ == "__main__":
    query_mysql_status()
    print "Query results have been saved to:", OUTPUT_FILE

 

标签:Python,数据库,sql,cursor,--,file,MySQL,query
From: https://www.cnblogs.com/dll102/p/18369438

相关文章

  • Python、R用RFM模型、机器学习对在线教育用户行为可视化分析|附数据、代码
    全文链接:https://tecdat.cn/?p=37409原文出处:拓端数据部落公众号分析师:ChunniWu随着互联网的不断发展,各领域公司都在拓展互联网获客渠道,为新型互联网产品吸引新鲜活跃用户,刺激用户提高购买力,从而进一步促进企业提升综合实力和品牌影响力。然而,为了更好地了解产品的主要受众群......
  • MySQL操作
    数据库类型常用数据类型详细数据类型需要注意的是:BOOLEAN在数据库保存的是tinyInt类型,false为0,true就是1char是定长,varchar是变长,char存储时,如果字符数没有达到定义的位数,后面会用空格填充到指定长度,而varchar没达到定义位数则不会填充,按实际长度存储。比如一个char(1......
  • TreeView和ListView数据库查询数据联动操作
    好久不用了,重新整理下放这里以备需要使用,功能见图数据库表结构定义TreeViewaddObject中data存储的记录集typePNode=^TNode;TNode=recordid:Integer;tcmc:string;mxid:string;end;填充TreeView代码procedureTForm1.FillTree(TreeV......
  • oracle & mysql 驱动程序安装配置
    Install-PackageOracle.ManagedDataAccess-Version12.2.20230118  版本可以安装到19.18Install-PackageMySql.Data-Version8.0.32.1config文件新增内容<system.data>  <DbProviderFactories>    <removeinvariant="MySql.Data.MySqlClient"/>    &......
  • FLink1.17-Kafka实时同步到MySQL实践
    1.组件版本组件版本Kafka3.7.0Flink1.17.0MySQL8.0.32 2.Kafka生产数据./kafka-console-producer.sh--broker-listhadoop01:9092,hadoop02:9092,hadoop03:9092--topic  kafka_test_table2>{"id":123,"test_age":33}&......
  • MySQL-MGR实战指南:打造企业级高可用数据库集群
    文章目录前言MGR的介绍事务处理流程:实验测试环境:结束语前言在数字化时代,企业的数据安全和业务连续性至关重要。想象一下,当关键业务数据存储在数据库中,而数据库突然出现故障,或者面临硬件故障、网络中断、自然灾害等不可预知的灾难性事件时,企业如何确保数据的完整性和......
  • Linux(CentOS7)安装MySQL8全过程
    下载官方地址:https://dev.mysql.com/downloads/mysql/选择版本前需先看一下服务器的glibc版本ldd--version  上传将下载好的tar包上传到服务器上,这里演示上传到了/usr/local/文件夹下 解压tar -Jxvfmysql-8.0.36-linux-glibc2.17-x86_64.tar.xz ......
  • mysql错误-The server quit without updating PID file
    说明:尽量不要用root用户安装和启动mysql问题示例原因:一般是root用户执行导致,如果MySQL是root以外用户安装的,则用安装的用户执行不会出差固执:这里就是要用root执行。[root@hadoop01mysql]#servicemysqlstartStartingMySQL.Loggingto'/opt/mysql/data/hadoop01.err'.......
  • python异步
    fastapi是一个异步的web框架。Starlette是一个轻量级、快速的PythonASGI框架,专为构建高性能异步Web应用和微服务而设计。它是FastAPI的核心依赖之一,许多FastAPI的功能都基于Starlette提供的组件。Starlette以其简洁的设计和丰富的功能而著称,非常适合构建现代异步W......
  • 基于python+flask框架的家政服务网上预约与管理系统(开题+程序+论文) 计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景在快节奏的现代生活中,家政服务成为了许多家庭不可或缺的一部分,它极大地便利了人们的日常生活,提高了生活质量。然而,传统的家政服务预约方式......