Python - 创建表

Python - 创建表 首页 / Python3入门教程 / Python - 创建表

在本教程的这一部分中,无涯教程将创建新表Employee。建立连接对象时,必须提及数据库名称。

可以使用SQL的CREATE TABLE语句创建新表。在数据库PythonDB中,表Employee最初具有四列,即name,id,salary和department_id。

以下查询用于创建新表Employee。

>  create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int not null)

示例

import mysql.connector

#创建连接对象
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Learnfk",database = "PythonDB")

#创建光标对象
cur = myconn.cursor()

try:
    #创建一个名为 Employee 的表,该表具有四列,即名称、id、salary和Dept_id
    dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not null)")
except:
    myconn.rollback()

myconn.close()
Creating table

现在,可以检查表Employee是否存在于数据库中。

修改表

有时,可能忘记创建一些列,或者可能需要更新表架构。如果需要,可使用alter语句更改表架构。在这里将把branch_name列添加到表Employee中。以下SQL查询用于此目的。

alter table Employee add branch_name varchar(20) not null

考虑以下示例。

无涯教程网

import mysql.connector

#创建连接对象
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Learnfk",database = "PythonDB")

#创建光标对象
cur = myconn.cursor()

try:
    #将列branch_name添加到表 Employee
    cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
    myconn.rollback()

myconn.close()
Creating the table

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转Spring全家桶 -〔丁雪丰〕

编译原理之美 -〔宫文学〕

WebAssembly入门课 -〔于航〕

手把手带你搭建秒杀系统 -〔佘志东〕

Serverless进阶实战课 -〔静远〕

Vue 3 企业级项目实战课 -〔杨文坚〕

运维监控系统实战笔记 -〔秦晓辉〕

AI 应用实战课 -〔黄佳〕

程序员职业规划手册 -〔雪梅〕

好记忆不如烂笔头。留下您的足迹吧 :)