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 数据库!

相关推荐
pengyu22 分钟前
【Kotlin 协程修仙录 · 大乘境 · 后阶】 | 死锁天劫:协程同步原语与 ThreadLocal 迁移之道
android·kotlin
事圆则缓22 分钟前
Android 常用设计模式速查
android·设计模式
sickworm陈浩24 分钟前
日常修改,3秒生效:腾讯音乐 Android 秒编方案 Jugg 开源
android·编译原理·编译器
Android-Flutter31 分钟前
android PhoneWindow, DecorView 详解
android
宝杰X71 小时前
Android Umeng 16kb对齐
android
2601_966563521 小时前
NativeWasmTv超精简2m安装包 长效免费电视直播软件-支持老电视盒子安卓4.0
android·电视盒子
Knight_AL1 小时前
MySQL 递归 CTE:WITH RECURSIVE 用法详解
android·数据库·mysql
恋猫de小郭1 小时前
聊个比较有意思的 Flutter Web 问题
android·前端·flutter
stevenzqzq1 小时前
Compose 生命周期与副作用的核心奥秘
android·compose
2501_915918411 小时前
Flutter项目配置iOS混淆的详细步骤与工具推荐
android·flutter·ios·小程序·uni-app·cocoa·iphone