Python MySQL SQLServer操作

Python MySQL SQLServer操作

Python 可以通过 pymysql 连接 MySQL,通过 pymssql 连接 SQL Server。以下是基础操作和代码实战示例:


一、操作 MySQL:使用 pymysql

python 操作数据库流程

1. 安装库

bash 复制代码
pip install pymysql

2. 连接 MySQL 示例

python 复制代码
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. 安装库

bash 复制代码
pip install pymssql

2. 连接 SQL Server 示例

python 复制代码
# 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

四、代码实战整合

以下是操作两种数据库的统一代码:

python 复制代码
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 数据库!

相关推荐
张风捷特烈24 分钟前
每日一题 Flutter#5,6 | 两道 Widget 选择题
android·flutter
移动开发者1号29 分钟前
App主界面点击与跳转启动方式区别
android·kotlin
移动开发者1号31 分钟前
我用Intent传大图片时竟然崩了,怎么回事啊
android·kotlin
androidwork12 小时前
Android LinearLayout、FrameLayout、RelativeLayout、ConstraintLayout大混战
android·java·kotlin·androidx
每次的天空12 小时前
Android第十三次面试总结基础
android·面试·职场和发展
wu_android12 小时前
Android 相对布局管理器(RelativeLayout)
android
李斯维14 小时前
循序渐进 Android Binder(二):传递自定义对象和 AIDL 回调
android·java·android studio
androidwork14 小时前
OkHttp 3.0源码解析:从设计理念到核心实现
android·java·okhttp·kotlin
像风一样自由15 小时前
【001】frida API分类 总览
android·frida
casual_clover15 小时前
Android 之 kotlin 语言学习笔记四(Android KTX)
android·学习·kotlin