zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

PythonSQLite数据库 基本知识
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关键字指定要删除的行。