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个列:id
、name
和email
。id
列是主键,不能为空。
在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个值:id
、name
和email
。我们使用VALUES
关键字来指定这些值。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。