在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
关键字指定要删除的行。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。