Python中数据库编程
时间: 2023-08-27 18:07:43 浏览: 99
在Python中,可以使用多种库来连接、操作数据库。其中比较常用的是:
1. SQLite3:轻量级的嵌入式数据库,适合小型应用开发。
2. MySQLdb:用于连接MySQL数据库的Python库。
3. psycopg2:用于连接PostgreSQL数据库的Python库。
4. pyodbc:用于连接Microsoft SQL Server数据库的Python库。
下面以SQLite3为例,介绍Python中如何进行数据库编程:
1. 连接数据库
```python
import sqlite3
conn = sqlite3.connect('example.db')
```
2. 创建表
```python
c = conn.cursor()
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
```
3. 插入数据
```python
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
```
4. 提交事务
```python
conn.commit()
```
5. 查询数据
```python
c.execute('SELECT * FROM stocks')
print(c.fetchall())
```
6. 关闭连接
```python
conn.close()
```
以上是SQLite3的基本用法,其他库的用法类似。需要注意的是,不同的数据库可能有不同的语法和操作,需要查看对应的文档或者参考相关的教程。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![xmind](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)