Python Data Access 简明教程

Python SQLite - Create Table

使用 SQLite CREATE TABLE 语句,可以在数据库中创建一个表。

Using the SQLite CREATE TABLE statement you can create a table in a database.

Syntax

下面是创建 SQLite 数据库表的语法:

Following is the syntax to create a table in SQLite database −

CREATE TABLE database_name.table_name(
   column1 datatype PRIMARY KEY(one or more columns),
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype
);

Example

以下 SQLite 查询/语句在 SQLite 数据库中创建一个名为 CRICKETERS 的表:

Following SQLite query/statement creates a table with name CRICKETERS in SQLite database −

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 表中每个球员的一日板球统计数据。

Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table.

sqlite> CREATE TABLE ODIStats (
   First_Name VARCHAR(255),
   Matches INT,
   Runs INT,
   AVG FLOAT,
   Centuries INT,
   HalfCenturies INT
);
sqlite

可以使用 .tables 命令获取 SQLite 数据库中表的列表。在创建一个表之后,如果可以验证表列表,你可以观察到其中新建的表,如下所示:

You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as −

sqlite> . tables
CRICKETERS ODIStats
sqlite>

Creating a table using python

游标对象包含用于执行查询和获取数据等的所有方法。连接类的游标方法返回一个游标对象。

The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object.

因此,要在 Python 中创建 SQLite 数据库中的表:

Therefore, to create a table in SQLite database using python −

  1. Establish connection with a database using the connect() method.

  2. Create a cursor object by invoking the cursor() method on the above created connection object.

  3. Now execute the CREATE TABLE statement using the execute() method of the Cursor class.

Example

以下 Python 程序在 SQLite3 中创建一个名为 Employee 的表:

Following Python program creates a table named Employee in SQLite3 −

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()

Output

Table created successfully........