- Python 数据访问教程
- Python 数据访问 - 主页
- Python MySQL
- Python MySQL - 简介
- Python MySQL - 数据库连接
- Python MySQL - 创建数据库
- Python MySQL - 创建表
- Python MySQL - 插入数据
- Python MySQL - 选择数据
- Python MySQL -Where 子句
- Python MySQL - 排序依据
- Python MySQL - 更新表
- Python MySQL - 删除数据
- Python MySQL - 删除表
- Python MySQL - 限制
- Python MySQL - 加入
- Python MySQL - 游标对象
- Python PostgreSQL
- Python PostgreSQL - 简介
- Python PostgreSQL - 数据库连接
- Python PostgreSQL - 创建数据库
- Python PostgreSQL - 创建表
- Python PostgreSQL - 插入数据
- Python PostgreSQL - 选择数据
- Python PostgreSQL -Where 子句
- Python PostgreSQL - 排序依据
- Python PostgreSQL - 更新表
- Python PostgreSQL - 删除数据
- Python PostgreSQL - 删除表
- Python PostgreSQL - 限制
- Python PostgreSQL - 加入
- Python PostgreSQL - 游标对象
- Python SQLite
- Python SQLite - 简介
- Python SQLite - 建立连接
- Python SQLite - 创建表
- Python SQLite - 插入数据
- Python SQLite - 选择数据
- Python SQLite -Where 子句
- Python SQLite - 排序依据
- Python SQLite - 更新表
- Python SQLite - 删除数据
- Python SQLite - 删除表
- Python SQLite - 限制
- Python SQLite - 加入
- Python SQLite - 游标对象
- Python MongoDB
- Python MongoDB - 简介
- Python MongoDB - 创建数据库
- Python MongoDB - 创建集合
- Python MongoDB - 插入文档
- Python MongoDB - 查找
- Python MongoDB - 查询
- Python MongoDB - 排序
- Python MongoDB - 删除文档
- Python MongoDB - 删除集合
- Python MongoDB - 更新
- Python MongoDB - 限制
- Python 数据访问资源
- Python 数据访问 - 快速指南
- Python 数据访问 - 有用的资源
- Python 数据访问 - 讨论
Python SQLite - 创建表
使用 SQLite CREATE TABLE 语句可以在数据库中创建表。
句法
以下是在 SQLite 数据库中创建表的语法 -
CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype );
例子
以下 SQLite 查询/语句在 SQLite 数据库中创建一个名为CRICKETERS的表-
sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite>
让我们再创建一个表 OdiStats,描述 CRICKETERS 表中每个球员的一日板球统计数据。
sqlite> CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); sqlite
您可以使用.tables命令获取 SQLite 数据库中数据库中的表列表。创建表后,如果您可以验证表列表,您可以观察其中新创建的表:
sqlite> . tables CRICKETERS ODIStats sqlite>
使用 python 创建表
Cursor对象包含执行查询、获取数据等的所有方法。连接类的cursor方法返回一个游标对象。
因此,要使用 python 在 SQLite 数据库中创建表 -
使用 connect() 方法与数据库建立连接。
通过在上面创建的连接对象上调用cursor()方法来创建游标对象。
现在使用 Cursor 类的execute() 方法执行CREATE TABLE 语句。
例子
以下 Python 程序在 SQLite3 中创建一个名为 Employee 的表 -
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
)'''
cursor.execute(sql)
print("Table created successfully........")
# Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
输出
Table created successfully........