python连接mysql
时间: 2023-09-03 16:09:25 浏览: 47
要连接MySQL,必须安装MySQL驱动程序。Python标准的MySQL驱动程序是mysql-connector-python。
1. 安装mysql-connector-python
```
pip install mysql-connector-python
```
2. 导入MySQL驱动程序
```
import mysql.connector
```
3. 连接MySQL
```
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
4. 创建游标对象
```
mycursor = mydb.cursor()
```
5. 执行SQL语句
```
mycursor.execute("SELECT * FROM customers")
```
6. 获取结果
```
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
完整代码示例:
```
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
阅读全文