Python操作MSSQL数据库

# !/usr/bin/env python3
# _*_ encoding: utf-8 _*_
# FileName :mssqlhandle.py
# Time     :2021-03-05 09:40
# ++++++++++++++++++++++++++++++++++++++++++++++++++
# 调用.sql文件 执行
# 使用方法 python3 mssqlhandle.py  ODS_SAP_EHR2_DC_HRP9350
# param: 表名称
# ++++++++++++++++++++++++++++++++++++++++++++++++++
import configparser
import datetime
import sys
import time
from functools import wraps

import pymssql

workPath = "/data/etl/ETLAuto"


def decorator(function):
    @wraps(function)
    def inner(*args, **kwargs):
        try:
            print('当前运行: ', function.__name__)
            return function(*args, **kwargs)
        except Exception as e:
            print(e.args[-1])
            sys.exit(-1)

    return inner


def echoRuntime(func):
    def wrapper(*args, **kwargs):
        startTime = time.time()
        func(*args, **kwargs)
        endTime = time.time()
        messcs = (endTime - startTime)
        print(func.__name__ + ' running time is : %.4f' % messcs)

    return wrapper


class HandleDB(object):
    """docstring for HandleDB"""

    def __init__(self, file_path=None):
        super(HandleDB, self).__init__()
        if file_path:
            configpath = file_path
        else:
            configpath = workPath + '/app/conf.ini'
            print('配置文件路径: ', configpath)
        self.cf = configparser.ConfigParser()
        self.cf.read(configpath)

    def execute_sql(self, sqlCode):
        """:param 连接数据库"""
        with pymssql.connect(host='192.168.2.112', port=1433, user='SA', password='1234asdF'
                , database='master') as conn:
            with conn.cursor() as cursor:
                print(sqlCode)
                cursor.execute(sqlCode)
                # print(cursor.fetchone())

    def insert_sqlfile(self, table_name):
        sqlCode = "DELETE FROM dbo.auzre_task_control WHERE mpp_schema = '%s' AND run_date = '%s'; INSERT INTO dbo.auzre_task_control (mpp_schema, tablename, run_date, ods_schema, ods_tablename, data_load_start_time, data_load_end_time, data_load_status) VALUES('public', '%s', '%s', 'dbo', '%s', '', '', ''); " % (
            table_name, datetime.datetime.today().strftime('%Y-%m-%d'), table_name,
            datetime.datetime.today().strftime('%Y-%m-%d'), table_name)
        # print(sqlCode)
        self.execute_sql(sqlCode)


@echoRuntime
@decorator
def main():
    print('开始执行:%s' % (datetime.datetime.now()))
    table_name = sys.argv[1]
    obj = HandleDB()
    obj.insert_sqlfile(table_name)
    print('执行结束:%s' % (datetime.datetime.now()))


if __name__ == '__main__':
    print('Life Is Short! I Use Python!')
    main()
    # obj = HandleDB()
    # obj.insert_sqlfile('test_ods_db')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Python中连接到Microsoft SQL Server数据库,我们需要使用pyodbc模块。以下是连接到MSSQL的基本步骤: 1. 安装pyodbc模块:在命令行中使用pip install pyodbc命令安装pyodbc模块。 2. 安装ODBC驱动程序:在Windows上,需要安装Microsoft ODBC Driver for SQL Server驱动程序。在Linux上,可以使用FreeTDS驱动程序。 3. 导入pyodbc模块:在Python脚本中导入pyodbc模块。 4. 连接到数据库:使用pyodbc.connect()函数连接到数据库。需要提供数据库的DSN(数据源名称)和其他连接参数。 5. 创建游标对象:使用connection.cursor()方法创建游标对象。 6. 执行查询:使用游标对象的execute()方法执行SQL查询语句。 7. 处理结果集:使用游标对象的fetchall()方法获取查询结果集。 以下是一个简单的Python代码示例,用于连接到MSSQL数据库,并执行一个简单的查询: ``` import pyodbc # Connect to database connection = pyodbc.connect('DSN=MyDSN;UID=myuser;PWD=mypassword') # Create cursor cursor = connection.cursor() # Execute query cursor.execute('SELECT * FROM mytable') # Get results results = cursor.fetchall() # Print results for row in results: print(row) # Close connection connection.close() ``` 在上面的代码中,我们使用pyodbc.connect()函数连接到名为MyDSN的数据库,并提供用户名和密码。我们使用connection.cursor()方法创建游标对象,并使用游标对象的execute()方法执行SELECT查询。最后,我们使用游标对象的fetchall()方法获取结果集,并使用for循环打印每一行结果。最后,我们使用connection.close()方法关闭数据库连接。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值