Python 连接MySQL数据库
时间: 2023-06-19 13:09:28 浏览: 120
Python连接MYSQL
5星 · 资源好评率100%
在 Python 中连接 MySQL 数据库需要使用 MySQL Connector 模块,具体步骤如下:
1. 安装 MySQL Connector 模块
```
pip install mysql-connector-python
```
2. 导入 MySQL Connector 模块
```python
import mysql.connector
```
3. 建立连接
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
4. 创建游标对象
```python
mycursor = mydb.cursor()
```
5. 执行 SQL 查询
```python
mycursor.execute("SELECT * FROM yourtable")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
6. 关闭连接
```python
mydb.close()
```
完整示例代码:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM yourtable")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
mydb.close()
```
阅读全文