求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Modeler   Code  
会员   
要资料
 
追随技术信仰

随时听讲座
每天看新闻
 
 
Python MySQL教程
1. Python_MySQL入门
2. Python 创建数据库
3. Python 创建表
4. Python 插入表
5. Python 从表中选取
6. Python 使用筛选器来选取
7. Python 结果排序
8. Python 删除记录
9. Python 删除表
10. Python 更新表
11. Python 限定结果
12. Python 加入
 

 
目录
Python 创建表
46 次浏览
4次  

创建表

如需在 MySQL 中创建表,请使用 "CREATE TABLE" 语句。

请确保在创建连接时定义数据库的名称。

实例

创建表 "customers":

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

运行实例 »

如果执行上面的代码没有错误,那么您现在已经成功创建了一个表。

检查表是否存在

您可以通过使用 "SHOW TABLES" 语句列出数据库中的所有表,来检查表是否存在:

实例

返回系统中的数据库列表:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
  print(x)

运行实例 »

主键

创建表时,您还应该为每条记录创建一个具有唯一键的列。

这可以通过定义 PRIMARY KEY 来完成。

我们使用语句 "INT AUTO_INCREMENT PRIMARY KEY",它将为每条记录插入唯一的编号。从 1 开始,每个记录递增 1。

实例

创建表时创建主键:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(255), address VARCHAR(255))")

运行实例 »

如果表已存在,请使用 ALTER TABLE 关键字:

实例

在已有的表上创建主键:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

运行实例 »


您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码: 验证码,看不清楚?请点击刷新验证码 必填



46 次浏览
4次