pyhton如何连接mysql
时间: 2023-10-16 19:09:52 浏览: 77
要在Python中连接MySQL数据库,需要先安装相应的数据库驱动程序。常用的MySQL数据库驱动程序有MySQL Connector、PyMySQL、mysqlclient等。这里以MySQL Connector为例进行介绍,并假设你已经安装了MySQL数据库和Python环境。
1. 安装MySQL Connector
使用pip命令安装MySQL Connector:
```
pip install mysql-connector-python
```
2. 连接数据库
在Python中使用MySQL Connector连接数据库,需要指定数据库的主机、端口、用户名、密码等信息。代码示例如下:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="databasename"
)
# 获取游标对象
mycursor = mydb.cursor()
# 执行SQL语句
mycursor.execute("SELECT * FROM table")
# 获取查询结果
myresult = mycursor.fetchall()
# 输出查询结果
for x in myresult:
print(x)
```
其中,`host`为数据库主机名,`user`和`password`为数据库的用户名和密码,`database`为要连接的数据库名。连接成功后,使用`cursor`方法获取游标对象,再使用`execute`方法执行SQL语句,最后使用`fetchall`方法获取查询结果。
阅读全文
相关推荐
![](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)
![](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)
![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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)