📅  最后修改于: 2023-12-03 14:47:39.360000             🧑  作者: Mango
SQLite is a powerful, lightweight relational database management system that is widely used in various software applications. In this article, we will be discussing how to install SQLite in Python and how to use it to execute SQL statements.
To install SQLite in Python, you need to have Python installed on your machine. After that, you can easily install SQLite using the following command:
pip install sqlite3
This will install the latest version of SQLite that is compatible with Python.
If you are using Python 2, you can install SQLite using the following command:
pip install pysqlite
Once you have installed SQLite in Python, you can start using it to execute SQL statements. First, you need to import the SQLite library:
import sqlite3
After that, you can create a connection to a SQLite database using the following code:
conn = sqlite3.connect('database.db')
This will create a connection to the 'database.db' file. If the file does not exist, it will be created.
Next, you can create a cursor object that allows you to execute SQL statements:
cur = conn.cursor()
Now you can execute SQL statements using the cursor object. For example, the following code creates a table in the database:
cur.execute('''CREATE TABLE customers
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
conn.commit()
This will create a table called 'customers' with three columns: 'id', 'name', and 'email'.
You can also insert data into the table using the following code:
cur.execute('''INSERT INTO customers
(name, email)
VALUES (?, ?)''',
('John Doe', 'john.doe@example.com'))
conn.commit()
This will insert a new record into the 'customers' table.
Finally, you can retrieve data from the table using the following code:
cur.execute('''SELECT * FROM customers''')
rows = cur.fetchall()
for row in rows:
print(row)
This will retrieve all the records from the 'customers' table and print them to the console.
In this article, we discussed how to install SQLite in Python and how to use it to execute SQL statements. SQLite is a powerful database management system that is widely used in various software applications. By following the steps outlined in this article, you can easily integrate SQLite into your Python applications.