话不多说,有图有源码
1)确保本机安装了sql server对应的odbc驱动
在控制面板的管理工具中可以查:数据源(ODBC)
我这里已经安装了,如果没有安装可以自行下载安装
2)连接MsSql Server代码
# -*- coding: utf-8 -*-
__author__ = "阿桂天山"
#----------判断连接是否正常
from sqlalchemy import (Table, MetaData, create_engine,
Column, Integer, String, SmallInteger, DateTime, text)
from datetime import datetime
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy.exc import OperationalError,InternalError
#----------测试连接mssqlserver
def try_linkMSSqldb(username,password,hostip,hostport,dbname):
DRIVER = "ODBC Driver 18 for SQL Server"
USERNAME = username
PSSWD = password
SERVERNAME = hostip
PORT=hostport
INSTANCENAME = "\SQLEXPRESS"
DB = dbname
engine = create_engine(f"mssql+pyodbc://{USERNAME}:{PSSWD}@{SERVERNAME}{INSTANCENAME}:{PORT}/{DB}?driver={DRIVER}&TrustServerCertificate=yes", fast_executemany=True)
metadata = MetaData()
try:
metadata.reflect(schema=DB, bind=engine)
return "连接成功!"
except Exception as e:
return repr(e)
#----------测试
print(try_linkMSSqldb('sa','aabbCC123xxx','127.0.0.1','1433','SQLTEST'))
最后,运行结果
相信上面的代码对你一定有所帮助,点赞吧!!!