python dbUtil

# -*- coding: utf-8 -*-    


import pyodbc
import cx_Oracle


class Database:
    def __init__(self, driver, server, database, username, password):
        """
        链接数据库
        :param driver:  数据库驱动
        :param server: 地址:端口
        :param database: 数据库名称
        :param username: 用户名
        :param password: 密码
        """
        self.driver = driver
        self.database = database
        if self.database.upper() == '数据库':
            self.server = "地址:端口"
            self.username = "用户名"
            self.password = "密码"
        else:
            self.server = server
            self.database = database
            self.username = username
            self.password = password
        self.connection = None
        self.cursor = None

    def prepare(self, query):
        """
        准备查询语句
        """
        try:
            self.cursor.prepare(query)
        except Exception as e:
            print(f"准备查询语句时发生错误: {e}")

    def connect(self):
        """
        连接数据库
        """
        try:
            if self.driver == "ODBC Driver 17 for SQL Server":
                self.connection = pyodbc.connect(
                    f"DRIVER={{{self.driver}}};SERVER={self.server};DATABASE={self.database};UID={self.username};PWD={self.password}"
                )
            elif self.driver == "Oracle":
                self.connection = cx_Oracle.connect(
                    f"{self.username}/{self.password}@{self.server}/{self.database}"
                )
            self.cursor = self.connection.cursor()
        except Exception as e:
            print(f"连接数据库时出错: {e}")

    def execute_query(self, query):
        """
        执行查询语句
        """
        try:
            self.cursor.execute(query)
            return self.cursor.fetchall()
        except Exception as e:
            print(f"执行查询语句时出错: {e}")

    def execute_non_query(self, query):
        """
        执行非查询语句
        """
        try:
            self.cursor.prepare(query)
            self.cursor.execute(query)
            self.connection.commit()
        except Exception as e:
            print(f"执行非查询语句时出错: {e} | Error line: [{e.__traceback__.tb_lineno}]")

    def get_table_count(self, table_name, where_clause=None):
        """
        获取表总数
        """
        try:

            if where_clause:
                query = f"SELECT COUNT(*) FROM {table_name} where {where_clause}"
            else:
                query = f"SELECT COUNT(*) FROM {table_name}"
            self.cursor.execute(query)
            return self.cursor.fetchone()[0]
        except Exception as e:
            print(f"获取表总数时出错: {e}")

    def execute_batch_insert(self, table_name, data):
        """
        执行批量插入语句
        """
        try:
            query = f"INSERT INTO {table_name} VALUES "
            for row in data:
                query += f"({','.join([str(val) for val in row])}),"
            query = query[:-1]  # 去掉最后一个逗号
            self.cursor.execute(query)
            self.connection.commit()
        except Exception as e:
            print(f"执行批量插入语句时出错: {e}")

    def execute_many(self, query, params):
        """
        执行多个参数的查询语句
        """
        try:
            # print(query, params)
            self.cursor.executemany(query, params)
            self.connection.commit()
        except Exception as e:
            print(f"执行多个参数的sql语句时出错: {e}")

    # def call_stored_procedure(self, procedure_name, params):
    #     """
    #     调用存储过程
    #     """
    #     try:
    #         self.cursor.callproc(procedure_name, params)
    #         self.connection.commit()
    #     except Exception as e:
    #         print(f"调用存储过程时出错: {e}")

    def call_stored_procedure(self, procedure_name, params=None):
        """
        调用存储过程
        """
        try:
            if params:
                if self.driver == "ODBC Driver 17 for SQL Server":
                    self.cursor.execute(f"EXEC {procedure_name} {','.join(['?' for _ in params])}", params)
                elif self.driver == "Oracle":
                    self.cursor.callproc(procedure_name, params)
            else:
                if self.driver == "ODBC Driver 17 for SQL Server":
                    self.cursor.execute(f"EXEC {procedure_name}")
                elif self.driver == "Oracle":
                    self.cursor.callproc(procedure_name)
            self.connection.commit()
        except Exception as e:
            print(f"调用存储过程时出错: {e}")

    def __del__(self):
        """
        关闭连接
        """
        try:
            if self.cursor:
                self.cursor.close()
            if self.connection:
                self.connection.close()
        except Exception as e:
            self.cursor.close()
            self.connection.close()
            print(f"关闭连接时出错: {e}")


def read_sql_file(file_path):
    """
    读取sql文件
    D:\Desktop\待办sql.sql文件格式为文本文件,包含SQL查询语句,每条语句以分号结尾
    :param file_path:
    :return:
    """
    try:
        with open(file_path, 'r') as f:
            sql = f.read()
            # print(sql)
        return sql
    except Exception as e:
        print(f"读取SQL文件时出错: {e}")
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python DBUtils 是一个轻量级的 Python 数据库连接池库,支持多个线程和多个进程,并可与各种数据库后端一起使用。DBUtils 是一个纯 Python 库,没有其他依赖项。 DBUtils 的主要目的是提供一个共享数据库连接池,这样可以避免在不同的线程和进程中频繁地打开和关闭数据库连接。这可以极大地提高应用程序的性能和响应速度。 DBUtils 提供了一些常见的数据库连接池实现,包括 PooledDB,PersistentDB 和 StackedObjectPool。这些实现都提供了相同的接口,因此可以很容易地将它们用于不同的应用程序。 使用 DBUtils 可以在保持代码简洁的同时获得数据库连接池的好处。以下是一个使用 DBUtils 连接 MySQL 数据库的示例: ```python import pymysql from dbutils.pooled_db import PooledDB POOL = PooledDB( creator=pymysql, maxconnections=5, mincached=2, maxcached=5, blocking=True, maxusage=None, host='localhost', port=3306, user='root', password='password', database='test', charset='utf8mb4' ) def get_conn(): return POOL.connection() def query_data(sql): conn = get_conn() cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() conn.close() return result ``` 在上面的示例中,我们使用 `PooledDB` 创建了一个 MySQL 数据库连接池,并使用 `get_conn` 获取一个连接对象,然后使用 `query_data` 函数执行 SQL 查询。注意,我们在使用完连接后需要手动关闭连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值