Python MySQL SQLServer操作
Python 可以通过 pymysql 连接 MySQL,通过 pymssql 连接 SQL Server。以下是基础操作和代码实战示例:
一、操作 MySQL:使用 pymysql
 
python 操作数据库流程

1. 安装库
pip install pymysql
2. 连接 MySQL 示例
import pymysql
# 连接数据库
connection = pymysql.connect(
    host='localhost',         # 数据库主机
    user='root',              # 用户名
    password='password',      # 密码
    database='test_db',       # 数据库名称
    charset='utf8mb4',        # 编码
    cursorclass=pymysql.cursors.DictCursor
)
try:
    with connection.cursor() as cursor:
        # 创建表
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100),
            age INT
        )
        """)
        # 插入数据
        cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('Alice', 30))
        connection.commit()
        # 查询数据
        cursor.execute("SELECT * FROM users")
        result = cursor.fetchall()
        print(result)
finally:
    connection.close()
二、操作 SQL Server:使用 pymssql
 
1. 安装库
pip install pymssql
2. 连接 SQL Server 示例
# 1. 导入pymysql模块
import pymysql
# 2. 创建连接对象
# host:连接的mysql主机,如果本机是’localhost’
# port:连接的mysql主机的端口,默认是3306
# database:数据库的名称
# user:连接的用户名
# password:连接的密码
# charset:通信采用的编码方式,推荐使用utf8
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="mysql",
                       database="python41",
                       charset="utf8"
                       )
# 3.获取游标,目的就是要执行sql语句
cursor = conn.cursor()
# 准备sql,之前在mysql客户端如何编 写sql,在python程序里面还怎么编写
sql = "select * from students;"
# 4. 执行sql语句
cursor.execute(sql)
# 获取查询结果,返回的数据类型是一个元组:(1,张三)
row = cursor.fetchone()
print(row)
# 5.关闭游标
cursor.close()
# 6.关闭连接
conn.close()
三、关键点对比
| 功能 | pymysql | pymssql | 
|---|---|---|
| 安装 | pip install pymysql | pip install pymssql | 
| 驱动协议 | MySQL 协议 | TDS(Tabular Data Stream)协议 | 
| SQL 查询语法支持 | 支持标准 SQL | 支持 SQL Server 特有语法 | 
| 默认端口 | 3306 | 1433 | 
四、代码实战整合
以下是操作两种数据库的统一代码:
import pymysql
import pymssql
# MySQL 数据库操作
def operate_mysql():
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='test_db',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM users")
            result = cursor.fetchall()
            print("MySQL 数据:", result)
    finally:
        connection.close()
# SQL Server 数据库操作
def operate_sqlserver():
    connection = pymssql.connect(
        server='localhost',
        user='sa',
        password='password',
        database='test_db'
    )
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM users")
            result = cursor.fetchall()
            print("SQL Server 数据:", result)
    finally:
        connection.close()
# 调用函数
operate_mysql()
operate_sqlserver()
通过以上代码,您可以在 Python 中灵活地操作 MySQL 和 SQL Server 数据库!


















