Python联接数据库代码
时间: 2024-06-05 07:04:31 浏览: 14
Python可以通过各种数据库API连接数据库,以下是使用MySQL数据库为例的示例代码:
1. 安装MySQL Connector Python:`pip install mysql-connector-python`
2. 导入MySQL Connector Python:`import mysql.connector`
3. 建立数据库连接:`cnx = mysql.connector.connect(user='username', password='password', host='host', database='database_name')`
其中,`username`和`password`分别为你的用户名和密码,`host`为你的数据库主机地址,`database_name`为你要连接的数据库名称。
4. 创建游标对象:`cursor = cnx.cursor()`
5. 执行SQL查询:`cursor.execute("SELECT * FROM table_name")`
6. 获取查询结果:`result = cursor.fetchall()`
7. 关闭游标和数据库连接:`cursor.close()`, `cnx.close()`
完整示例代码如下:
```
import mysql.connector
# 建立数据库连接
cnx = mysql.connector.connect(user='username', password='password', host='host', database='database_name')
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM table_name")
# 获取查询结果
result = cursor.fetchall()
# 关闭游标和数据库连接
cursor.close()
cnx.close()
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)