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查询用于此目的。

链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-mysql-creating-tables.html

来源:LearnFk无涯教程网

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

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

教程推荐

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

JavaScript进阶实战课 -〔石川〕

React Native 新架构实战课 -〔蒋宏伟〕

程序员的个人财富课 -〔王喆〕

A/B测试从0到1 -〔张博伟〕

苏杰的产品创新课 -〔苏杰〕

Node.js开发实战 -〔杨浩〕

深入拆解Tomcat & Jetty -〔李号双〕

深入浅出区块链 -〔陈浩〕

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