深度阅读

How to Execute a SQLite Statement in Python?

作者
作者
2023年08月22日
更新时间
12.34 分钟
阅读时间
0
阅读量

To execute a SQLite statement in Python, you can use the execute() method of a Cursor object from the sqlite3 module. Here’s an example:

import sqlite3

# Open a connection to a SQLite database
conn = sqlite3.connect('example.db')

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

# Execute a SQLite statement
cursor.execute("CREATE TABLE person (name TEXT, age INTEGER)")

# Commit the changes to the database
conn.commit()

# Close the connection
conn.close()

In this example, we first establish a connection to a SQLite database file called example.db using the sqlite3.connect() method. We then create a Cursor object using the cursor() method and execute a SQLite statement to create a table called person with two columns: name of type TEXT and age of type INTEGER. We then commit the changes to the database using the commit() method and close the connection using the close() method.

Note that to execute a query or a non-query SQL statement using execute(), you need to pass in the SQL statement as a string argument. If you want to execute a SQL statement with parameters, you can use the parameter substitution syntax supported by the Python str.format() method or f-strings.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。