Python MySQL SQLServer操作

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()


三、关键点对比

功能pymysqlpymssql
安装pip install pymysqlpip install pymssql
驱动协议MySQL 协议TDS(Tabular Data Stream)协议
SQL 查询语法支持支持标准 SQL支持 SQL Server 特有语法
默认端口33061433

四、代码实战整合

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忘忧记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值