← 返回首页

pymssql链接sqlserver数据库

📖 正文内容

注意:有时候出现20002错误。是把yao版本降到2.27才行
在终端运行以下安装
pip3 install pymssql==2.2.7 -i https://pypi.mirrors.ustc.edu.cn/simple/

import pymssql def connect_to_database(server, user, password, database):     try:         # 创建数据库连接         conn = pymssql.connect(             server=server,             user=user,             password=password,             database=database         )                 # 打印成功信息         print("Connected successfully")                 # 返回连接对象         return conn     except pymssql.OperationalError as e:         # 打印错误信息         print(f"Connection error: {e}")         return None # 连接参数 server = 'your_server_ip_or_name' user = 'your_username' password = 'your_password' database = 'your_database' # 连接到数据库 conn = connect_to_database(server, user, password, database) if conn:     # 创建游标     cursor = conn.cursor()         # 执行查询     cursor.execute("SELECT * FROM your_table")         # 获取结果     rows = cursor.fetchall()         # 打印结果     for row in rows:         print(row)         # 关闭游标和连接     cursor.close()     conn.close() else:     print("Failed to connect to the database.")

💡 示例代码

<div style='--en-codeblock:true;--en-blockId:GXqXSO5j8k_;--en-meta:{"title":"","lang":"Plain Text","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>import pymssql

def connect_to_database(server, user, password, database):
    try:
        # 创建数据库连接
        conn = pymssql.connect(
            server=server,
            user=user,
            password=password,
            database=database
        )
        
        # 打印成功信息
        print("Connected successfully")
        
        # 返回连接对象
        return conn
    except pymssql.OperationalError as e:
        # 打印错误信息
        print(f"Connection error: {e}")
        return None

# 连接参数
server = 'your_server_ip_or_name'
user = 'your_username'
password = 'your_password'
database = 'your_database'

# 连接到数据库
conn = connect_to_database(server, user, password, database)

if conn:
    # 创建游标
    cursor = conn.cursor()
    
    # 执行查询
    cursor.execute("SELECT * FROM your_table")
    
    # 获取结果
    rows = cursor.fetchall()
    
    # 打印结果
    for row in rows:
        print(row)
    
    # 关闭游标和连接
    cursor.close()
    conn.close()
else:
    print("Failed to connect to the database.")
</div>

💭 技巧提示

💡

📚 参考资料

💬 评论交流

👤
用户 A 2026-03-25

这个技巧很实用,感谢分享!