利用python对mysql数据库进行建表操作:可以同一个py文件下一次性创建多个表

环境:windows, python3.6, mysql5.7

1.安装相关的库

      pip install pymysql

2.新建build_table.py文件,下为案例代码

import pymysql

#获取数据库配置
db = pymysql.connect(
    host='localhost',
    database='novellist',  #库名
    user='root',
    password='123456',
    port=5200,
    charset='utf8'
    )

#使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()

#使用execute()方法执行sql,如果表存在则删除
# cursor.execute("drop table if exists novel")

#执行sql处理语句创建表
sql_novel = """create table novel(
id bigint not null primary key auto_increment,
bookname varchar(355) not null,
novel_url varchar(355) not null,
cover_url varchar(355) not null,
key novel_website_id_index (website_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;"""


# cursor.execute("drop table if exists chapter")
sql_chapter="""
create table chapter(
id bigint not null primary key auto_increment,
novel_id bigint not null,
chapter_name varchar(255) not null,
chapter_url varchar(255) not null,
chapter_uptime varchar(255) not null,
chapter longtext,
key chapter_novel_id_index (novel_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""

# cursor.execute("drop table if exists website")
sql_website="""
create table website(
id bigint not null primary key auto_increment,
website_url varchar(255) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""

#创建
cursor.execute(sql_novel)
cursor.execute(sql_chapter)
cursor.execute(sql_website)

#关闭数据库,无论对数据库如何操作,都要关闭数据库,防止出错
db.close()

3.运行

python build_table.py
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 11,295评论 0 10
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,736评论 6 427
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 9,701评论 4 16
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 8,175评论 1 3
  • 冰雪奇緣(Frozen)最近火得要命,主題曲「Let it go」更是紅得發紫。在我看來,這是一部迎合了美國左翼價...
    BYVoid阅读 4,001评论 0 2

友情链接更多精彩内容