Python连接MySQL
时间: 2023-11-15 21:05:16 浏览: 42
在Python中连接MySQL需要使用MySQL官方提供的Python驱动程序,称为MySQL Connector Python。
以下是连接MySQL的基本步骤:
1. 安装MySQL Connector Python驱动程序。你可以使用pip命令通过命令行安装它。命令如下:
```
pip install mysql-connector-python
```
2. 导入MySQL Connector Python驱动程序。
```python
import mysql.connector
```
3. 建立数据库连接。
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
```
4. 创建游标。
```python
mycursor = mydb.cursor()
```
5. 执行SQL语句。
```python
mycursor.execute("SELECT * FROM customers")
```
6. 获取结果。
```python
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
完整代码示例:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建游标
mycursor = mydb.cursor()
# 执行SQL语句
mycursor.execute("SELECT * FROM customers")
# 获取结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```