用Python写一个数据库接口
时间: 2024-03-06 13:22:08 浏览: 16
以下是一个使用Python的SQLite数据库接口的示例:
```python
import sqlite3
# connect to database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# create table
cursor.execute('''CREATE TABLE products
(id INTEGER PRIMARY KEY, name text, price real)''')
# insert data
cursor.execute("INSERT INTO products VALUES (1, 'Apple', 0.99)")
cursor.execute("INSERT INTO products VALUES (2, 'Banana', 0.59)")
cursor.execute("INSERT INTO products VALUES (3, 'Orange', 0.79)")
# commit changes
conn.commit()
# retrieve data
cursor.execute("SELECT * FROM products")
rows = cursor.fetchall()
for row in rows:
print(row)
# close connection
conn.close()
```
这个示例使用Python的SQLite库连接到一个名为"mydatabase.db"的数据库。它创建一个名为"products"的表,并插入三条数据。然后它检索所有数据,并将它们显示在控制台上。最后,连接关闭。