python sqlite3 基本操作
时间: 2023-12-24 07:03:32 浏览: 82
以下是Python3中使用sqlite3模块进行基本操作的示例:
1. 连接到数据库
```python
import sqlite3
conn = sqlite3.connect('example.db')
```
2. 创建表
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
conn.commit()
conn.close()
```
3. 插入数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
conn.close()
```
4. 查询数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
conn.close()
```
5. 更新数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("UPDATE stocks SET qty = 200 WHERE symbol = 'RHAT'")
conn.commit()
conn.close()
```
6. 删除数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("DELETE FROM stocks WHERE symbol = 'RHAT'")
conn.commit()
conn.close()
```
阅读全文