前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >python-Python与SQLite数据库-SQLite数据库的基本知识(一)

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

原创
作者头像
玖叁叁
发布2023-04-22 20:22:48
发布2023-04-22 20:22:48
45700
代码可运行
举报
文章被收录于专栏:玖叁叁玖叁叁
运行总次数:0
代码可运行

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

创建数据库

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

代码语言:javascript
代码运行次数:0
运行
复制
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的表格的示例:

代码语言:javascript
代码运行次数:0
运行
复制
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表格中插入一条数据的示例:

代码语言:javascript
代码运行次数:0
运行
复制
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关键字来指定这些值。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建数据库
  • 创建表格
  • 插入数据
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档