
在Python中使用SQLite数据库进行查询后,我们需要对查询结果进行处理,以便使用查询结果进行后续操作。
fetchone()获取单个结果如果查询结果只有一个行,我们可以使用fetchone()方法获取该行的值。以下是一个获取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 the first row
row = c.fetchone()
# Print the row
print(row)
# Close the cursor and the database connection
c.close()
conn.close()在上面的示例中,我们使用fetchone()方法获取customers表中的第一行,并使用print()函数打印该行的值。
fetchmany()获取多个结果如果查询结果有多行,我们可以使用fetchmany()方法获取指定数量的行。以下是一个获取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 two rows
rows = c.fetchmany(2)
# Print the rows
for row in rows:
print(row)
# Close the cursor and the database connection
c.close()
conn.close()在上面的示例中,我们使用fetchmany()方法获取customers表中的前两行,并使用一个循环遍历这两行,并打印它们的值。
fetchall()获取所有结果如果查询结果有多行,并且我们想获取所有行的值,我们可以使用fetchall()方法获取所有行的值。以下是一个获取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()在上面的示例中,我们使用fetchall()方法获取customers表中的所有行,并使用一个循环遍历所有行,并打印它们的值。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。