Python 连接MySQL数据库
时间: 2023-06-19 16:09:28 浏览: 116
Python连接Mysql数据库1
在 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()
```
阅读全文