pymysql执行DDL语句

pymysql对操作MySQL DDL数据库模式定义语言提供了很好的支持。

连接MySQL数据库后,可以使用cursor()方法创建一个游标对象。游标对象用于执行MySQL语句并返回结果。

基本用法

创建数据库、表:

复制代码
import pymysql

connection = None

try:
    # 建立数据库连接
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='root',
        database='test_db',
    )

    #游标对象
    cursor = connection.cursor()

    #创建数据库
    create_db_sql = "CREATE DATABASE IF NOT EXISTS mydatabase"
    cursor.execute(create_db_sql)
    print("数据库创建成功")

     # 选择数据库
    cursor.execute("USE mydatabase")

    # 创建表
    create_table_sql = """
         CREATE TABLE IF NOT EXISTS users (
             id INT AUTO_INCREMENT PRIMARY KEY,
             username VARCHAR(50) NOT NULL UNIQUE,
             email VARCHAR(100) NOT NULL,
             age INT,
             created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
             INDEX idx_username (username),
             INDEX idx_email (email)
         )
         """
    cursor.execute(create_table_sql)
    print("表创建成功")


except Exception as e:
    print(e)
finally:
    if connection:
        connection.close()

修改表结构:

复制代码
#向表中添加字段:alter table 表名 add [column] 字段名 字段类型:

alter table users add phone VARCHAR(20);

#删除表中的字段:alter table 表名 drop [column] 字段名:

alter table users drop phone;

#修改字段的名字:alter table 表名 change [column] 旧字段名 新字段名 字段类型:

alter table users change column username username2 varchar(20);

#修改字段的类型:alter table 表名 modify [column] 字段名 字段类型;

alter table users modify id varchar(20);

#修改表的名字:alter table 旧表名 rename to 新表名:
alter table users rename to users2;

增加字段代码示例:

复制代码
  #游标对象
    cursor = connection.cursor()

    alter_table_sql = """
           ALTER TABLE users 
           ADD COLUMN phone VARCHAR(20)
           """
    cursor.execute(alter_table_sql)
    print("增加字段成功")
相关推荐
玄同7651 天前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd1 天前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
火车叼位1 天前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位1 天前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
孤狼warrior1 天前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat996631 天前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威1 天前
农经权二轮延包—各种地块示意图
python·arcgis
ZH15455891311 天前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter
belldeep1 天前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask
喵手1 天前
Python爬虫实战:电商价格监控系统 - 从定时任务到历史趋势分析的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·电商价格监控系统·从定时任务到历史趋势分析·采集结果sqlite存储