python 连接SQL Server数据库

本文介绍使用Python通过pyodbc和pymssql两个库连接SQL Server的方法。详细展示了如何安装必要的库,配置连接参数,并执行基本的数据查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

### 使用Python连接SQL Server数据库 为了实现PythonSQL Server之间的通信,通常会借助`pyodbc`库。此库允许开发者编写跨平台的应用程序来访问不同的数据库管理系统(DBMS),包括Microsoft SQL Server。 #### 安装必要的依赖项 在Linux环境下,除了安装`pyodbc`外,还需要设置unixODBC以及FreeTDS作为底层的数据源名称(DSN)支持工具[^2]。对于Windows用户来说,则可以直接跳过这一步骤并仅需关注于pip包管理器中的组件安装: ```bash # 对于Linux系统而言,先执行如下命令以获取所需的驱动程序和支持文件: sudo apt-get install python3-pip unixodbc-dev freetds-dev tdsodbc ``` 接着,在任何操作系统上都可以继续通过pip安装Python端的接口模块: ```bash pip install pyodbc ``` #### 编写Python脚本连接SQL Server实例 一旦完成了上述准备工作之后,就可以利用下面给出的例子创建一个新的Python脚本来建立到目标SQL Server服务器上的链接了。这段代码展示了怎样定义连接字符串,并尝试打开一个新会话来进行查询操作。 ```python import pyodbc conn_str = ( "DRIVER={ODBC Driver 17 for SQL Server};" "SERVER=your_server_name_or_ip_address;" "DATABASE=your_database_name;" "UID=your_username;" "PWD=your_password" ) try: conn = pyodbc.connect(conn_str) cursor = conn.cursor() query = 'SELECT * FROM your_table' result_set = cursor.execute(query).fetchall() for row in result_set: print(row) except Exception as e: print(f'Error occurred while connecting to the database: {e}') finally: if 'conn' in locals(): conn.close() # Ensure that we close our connection when done. ``` 请注意替换掉上面模板里的占位符(`your_*`)为实际存在的对应值以便能够成功建立起有效的网络连接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值