python-Python与SQLite数据库-SQLite数据库的基本知识(二)
2023-06-13 09:18:47 时间
查询数据
在SQLite中,我们可以使用SQL语句查询表格中的数据。以下是一个从customers
表格中查询所有数据的示例:
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
列更新为新值的示例:
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
表格中删除第一行数据的示例:
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
关键字指定要删除的行。
相关文章
- 二级Python选择题_二级python选择题题库
- python skitlearn_Python sklearn
- python编程是什么-Python编程
- python清理浏览器缓存_以编程方式清除边缘浏览器缓存
- json转字符串 python_Python读取json
- gyp ERR! stack Error: Can't find Python executable 'python'
- python udp编程_Python核心编程
- python-Python与MySQL数据库-使用Python执行MySQL查询
- python-Python与SQLite数据库-使用Python执行SQLite查询(二)
- python-Python与SQLite数据库-处理SQLite查询结果(一)
- python-Python与SQLite数据库-处理SQLite查询结果(二)
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(二)
- Python 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)详解编程语言
- 一步一步学会在Linux上运行Python程序(linux运行python程序)
- 使用Python编程连接MySQL数据库(python连mysql)
- 在Linux上学习Python——你的编程之路(linux学python)
- 从Python连接Oracle数据库介绍(python连接oracle)
- Python实现Oracle数据库连接(python连接oracle数据库)
- 使用Python连接MySQL数据库,实现高效数据交互(python连接mysql)
- 转换MSSQL数据库至SQLite的实践探究(mssql转sqlite)