Python开发:使用pyodbc操作sqlsever数据库

from datetime import datetime
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-FTH2P3S;DATABASE=Millionaire;Trusted_Connection=yes;')
cursor = conn.cursor()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def sqlquery(sql):
    try:
        rows = cursor.execute(sql).fetchall()
        print(f"查询成功,数据:{len(rows)}条,时间:{now}")
        return rows
    except Exception as e:
        print(f"查询出现错误: {e},时间:{now}")

def sqlexecute(sql):
    try:
        cursor.execute(sql)
        cursor.connection.commit()
        print(f"增删改成功,时间:{now}")
    except Exception as e:
        print(f"增删改出现错误: {e},时间:{now}")
        cursor.connection.rollback()

if __name__ == '__main__':
    pass
    #入参
    # data = sqlquery("SELECT * FROM BuyTable WHERE ID='1'")
    # ins = 100
    # data = sqlquery(f"SELECT * FROM BuyTable WHERE ID={ins}")

你可能感兴趣的:(Python专栏,数据库,python,oracle)