如何用python连接mysql
时间: 2024-02-09 18:12:42 浏览: 17
要使用 Python 连接 MySQL 数据库,需要先安装 MySQL 驱动程序,可以使用 `pip` 安装 `mysql-connector-python` 驱动,具体步骤如下:
1. 打开终端或命令提示符,运行以下命令安装 `mysql-connector-python`:
```
pip install mysql-connector-python
```
2. 在 Python 中导入 `mysql.connector` 模块:
```python
import mysql.connector
```
3. 连接 MySQL 数据库:
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
其中,`host` 是 MySQL 服务器地址,`user` 是 MySQL 用户名,`password` 是 MySQL 密码,`database` 是要连接的数据库名称。
4. 执行 SQL 查询:
```python
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
在这个例子中,我们查询了 `customers` 表中的所有数据,并将结果打印在控制台上。
注意:确保将上述代码中的 `yourusername`,`yourpassword` 和 `yourdatabase` 替换为你的 MySQL 用户名、密码和数据库名称。