通过 python 执行 sql wj1
时间: 2023-10-06 18:09:11 浏览: 80
要在 Python 中执行 SQL,需要使用相应的数据库库,例如 MySQLdb、psycopg2、sqlite3 等。下面以 sqlite3 为例介绍如何执行 SQL:
1. 导入 sqlite3 库
```python
import sqlite3
```
2. 连接到数据库
```python
conn = sqlite3.connect('database.db')
```
其中,`database.db` 为数据库文件名,若文件不存在,则会自动创建。
3. 创建游标对象
```python
cursor = conn.cursor()
```
4. 执行 SQL
```python
sql = "SELECT * FROM table_name WHERE condition;"
cursor.execute(sql)
```
其中,`table_name` 为表名,`condition` 为查询条件。
5. 获取查询结果
```python
result = cursor.fetchall()
```
6. 关闭游标和数据库连接
```python
cursor.close()
conn.close()
```
完整代码示例:
```python
import sqlite3
# 连接到数据库
conn = sqlite3.connect('database.db')
# 创建游标对象
cursor = conn.cursor()
# 执行 SQL
sql = "SELECT * FROM table_name WHERE condition;"
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
# 关闭游标和数据库连接
cursor.close()
conn.close()
```
阅读全文
相关推荐


















