1. pyodbc包连接
pip install pyodbc 安装 pyodbc 包
指定驱动程序,安装ODBC 驱动 https://www.microsoft.com/en-us/download/details.aspx?id=50420
import pyodbc
cnxn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};' # 或 Driver={SQL Server}不需要安装
'Server=IP地址\sqlexpress;'
'Database=test11;'
'UID=sa;'
'PWD=123456;'
'Mars_Connection=Yes;')
cursors = cnxn.cursor()
cursors.execute("select * from Table_1")
rows = cursors.fetchall()
print(rows)
cnxn.close()
cursors.close()
2. pymssql包连接
pip install pymssql 下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/ 选择与Python相匹配版本
import pymssql
conn = pymssql.connect(
server="IP地址\sqlexpress",
user="sa",
password="123456",
database="test",
charset="utf8",
as_dict=True
)
cur = conn.cursor()
sql = "select * from Table_1 "
cur.execute(sql)
rows = cur.fetchall()
print(rows)
conn.close()
cur.close()
# functions
# connect参数:
def connect(*args, **kwargs): # real signature unknown
"""
Constructor for creating a connection to the database. Returns a
Connection object.
:param server: database host
:type server: string
:param user: database user to connect as. Default value: None.
:type user: string
:param password: user's password. Default value: None.
:type password: string
:param database: the database to initially connect to
:type database: string
:param timeout: query timeout in seconds, default 0 (no timeout)
:type timeout: int
:param login_timeout: timeout for connection and login in seconds, default 60
:type login_timeout: int
:param charset: character set with which to connect to the database
:type charset: string
:keyword as_dict: whether rows should be returned as dictionaries instead of tuples.
:type as_dict: boolean
:keyword appname: Set the application name to use for the connection
:type appname: string
:keyword port: the TCP port to use to connect to the server
:type port: string
:keyword conn_properties: SQL queries to send to the server upon connection
establishment. Can be a string or another kind
of iterable of strings
:keyword autocommit: Whether to use default autocommiting mode or not
:type autocommit: boolean
:keyword tds_version: TDS protocol version to use.
:type tds_version: string
"""
pass