To connect to an SQLite database from Python, you can use the sqlite3
module, which is part of the Python Standard Library. To create a connection to an SQLite database, you can use the connect()
method of the sqlite3
module, passing it the path to the database file. Here is an example:
import sqlite3
# create a connection to the database
conn = sqlite3.connect('my_database.db')
# create a cursor object that can be used to execute SQL statements
cursor = conn.cursor()
# execute a SQL query
cursor.execute('SELECT * FROM my_table')
# get the results of the query as a list of records
results = cursor.fetchall()
# loop through the results and print each record
for row in results:
print(row)
# close the connection to the database
conn.close()
This code assumes that you have an SQLite database file called
my_database.db
that contains a table called my_table
. This code also assumes that you have the necessary permissions to read and write to the database file. You can use the cursor
object to execute any other SQL queries you need, such as INSERT
, UPDATE
, or DELETE
.
Comments
Post a Comment