Python Database Write: Step-by-Step Guide
To write data into a database, one can use database modules in Python such as sqlite3, pymysql, psycopg2, etc. Below is an example code using the sqlite3 module to write data into a SQLite database:
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# 插入数据
cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', ('Alice', 25))
# 提交更改
conn.commit()
# 关闭连接
conn.close()
In this example, we start by connecting to the example.db database, then create a users table. Next, we insert a record into the table, and finally commit the changes and close the connection.
To use other database modules, you can perform corresponding operations based on the specific database type and connection method. For example, using the pymysql module to connect to a MySQL database, and using the psycopg2 module to connect to a PostgreSQL database.