Python连接数据库
时间: 2023-07-03 07:17:25 浏览: 133
要在 Python 中连接数据库,你需要安装相应的数据库驱动程序,并使用该驱动程序提供的 API 进行连接操作。下面以 MySQL 数据库为例,介绍如何在 Python 中连接 MySQL 数据库:
1. 安装 MySQL 驱动程序
Python 与 MySQL 数据库的连接需要使用 MySQL 官方提供的 Connector/Python 驱动程序。可以通过 pip 命令安装该驱动程序:
```
pip install mysql-connector-python
```
2. 连接 MySQL 数据库
使用以下代码连接 MySQL 数据库:
```
import mysql.connector
# 建立连接
cnx = mysql.connector.connect(user='username', password='password',
host='hostname',
database='database_name')
# 关闭连接
cnx.close()
```
其中,`username`、`password`、`hostname`、`database_name` 需要替换为实际的 MySQL 用户名、密码、主机名和数据库名。
3. 执行 SQL 查询
连接成功后,可以使用 `cursor()` 方法创建游标对象,然后使用该游标对象执行 SQL 查询:
```
import mysql.connector
# 建立连接
cnx = mysql.connector.connect(user='username', password='password',
host='hostname',
database='database_name')
# 创建游标对象
cursor = cnx.cursor()
# 执行 SQL 查询
query = ("SELECT * FROM table_name")
cursor.execute(query)
# 处理查询结果
for row in cursor:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
```
其中,`table_name` 需要替换为实际的表名。查询结果可以通过 `cursor` 对象迭代获取,每一行数据以元组的形式返回。
以上就是在 Python 中连接 MySQL 数据库的基本操作。其他数据库的连接方式和 API 可以参考相应的文档。
阅读全文
相关推荐
![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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)