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

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

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

查询数据

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

# Query the table
c.execute("SELECT * FROM customers")

# Fetch all rows
rows = c.fetchall()

# Print the rows
for row in rows:
    print(row)

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

在上面的示例中,我们使用execute()方法执行SQL语句来查询customers表格中的所有数据。然后,我们使用fetchall()方法获取所有行,并将它们存储在rows变量中。最后,我们使用一个循环遍历所有行,并打印它们的值。

更新数据

在SQLite中,我们可以使用SQL语句更新表格中的数据。以下是一个将customers表格中第一行数据的email列更新为新值的示例:

代码语言:javascript
代码运行次数:0
运行
复制
import sqlite3

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

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

# Update a row in the table
c.execute("UPDATE customers SET email='alice.new@example.com' WHERE id=1")

# Commit the changes
conn.commit()

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

在上面的示例中,我们使用execute()方法执行SQL语句来更新customers表格中第一行数据的email列。我们使用SET关键字来指定要更新的列和新值,并使用WHERE关键字指定要更新的行。

删除数据

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

# Delete a row from the table
c.execute("DELETE FROM customers WHERE id=1")

# Commit the changes
conn.commit()

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

在上面的示例中,我们使用execute()方法执行SQL语句来删除customers表格中第一行数据。我们使用DELETE关键字来指定要删除的行,并使用WHERE关键字指定要删除的行。

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 查询数据
  • 更新数据
  • 删除数据
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档