zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python-Python与SQLite数据库-SQLite数据库的基本知识(一)

PythonSQLite数据库 基本知识
2023-06-13 09:18:47 时间

SQLite是一种嵌入式关系型数据库,它是在本地计算机上存储数据的一种轻量级解决方案。在Python中,我们可以使用sqlite3模块来连接SQLite数据库,进行数据的读取、写入和更新等操作。

创建数据库

在SQLite中,我们可以使用sqlite3模块创建一个新的数据库。如果数据库不存在,则会创建一个新的数据库。以下是一个创建SQLite数据库的示例:

import sqlite3

# Create a connection to the database
conn = sqlite3.connect('example.db')

# Close the connection
conn.close()

在上面的示例中,我们使用connect()函数创建一个连接到名为example.db的SQLite数据库的连接。如果数据库不存在,则会自动创建一个新的数据库。最后,我们使用close()方法关闭连接。

创建表格

在SQLite中,我们可以使用SQL语句创建一个新的表格。以下是一个创建一个名为customers的表格的示例:

import sqlite3

# Create a connection to the database
conn = sqlite3.connect('example.db')

# Create a cursor object
c = conn.cursor()

# Create a table
c.execute('''CREATE TABLE customers
             (id INT PRIMARY KEY NOT NULL,
              name TEXT NOT NULL,
              email TEXT NOT NULL)''')

# Commit the changes
conn.commit()

# Close the cursor and the database connection
c.close()
conn.close()

在上面的示例中,我们使用execute()方法执行SQL语句来创建一个名为customers的表格。该表格包含3个列:idnameemailid列是主键,不能为空。

插入数据

在SQLite中,我们可以使用SQL语句向表格中插入数据。以下是一个向customers表格中插入一条数据的示例:

import sqlite3

# Create a connection to the database
conn = sqlite3.connect('example.db')

# Create a cursor object
c = conn.cursor()

# Insert a row into the table
c.execute("INSERT INTO customers (id, name, email) VALUES (1, 'Alice', 'alice@example.com')")

# Commit the changes
conn.commit()

# Close the cursor and the database connection
c.close()
conn.close()

在上面的示例中,我们使用execute()方法执行SQL语句来向customers表格中插入一条数据。该数据包含3个值:idnameemail。我们使用VALUES关键字来指定这些值。