Using Python to Operate SQLite
Using Python to operate SQLite database needs to rely on the 'sqlite3' module in the Standard library. The following is a complete Python code sample, including examples of connecting to a database, inserting data, querying, modifying, and deleting operations:
python
import sqlite3
#Connect to SQLite database
conn = sqlite3.connect('example.db')
#Create a cursor object
cursor = conn.cursor()
#Create Table
create_table_sql = '''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)
'''
cursor.execute(create_table_sql)
#Insert Data
insert_data_sql = '''
INSERT INTO users (name, age) VALUES (?, ?)
'''
cursor.execute(insert_data_sql, ('Alice', 25))
cursor.execute(insert_data_sql, ('Bob', 32))
#Query data
select_data_sql = '''
SELECT * FROM users
'''
cursor.execute(select_data_sql)
rows = cursor.fetchall()
for row in rows:
print(row)
#Modify data
update_data_sql = '''
UPDATE users SET age = ? WHERE name = ?
'''
cursor.execute(update_data_sql, (26, 'Alice'))
#Delete data
delete_data_sql = '''
DELETE FROM users WHERE name = ?
'''
cursor.execute(delete_data_sql, ('Bob',))
#Commit transaction
conn.commit()
#Close cursor and database connections
cursor.close()
conn.close()
In this example, first connect to the SQLite database using the 'sqlite3' module and create a table called 'users'. Then insert two pieces of data by executing the 'Insert' statement, query all data using the 'SELECT' statement, and modify and delete the data using the 'UPDATE' and 'DELETE' statements. Finally, use the 'commit ()' method to commit the transaction, close the cursor and database connection.
Note: This is only a simple example and may involve more complex operations and logical judgments in practical applications.