Python连接数据库MySQL
时间: 2023-06-19 07:05:28 浏览: 86
要使用Python连接MySQL数据库,需要安装MySQL驱动程序。常用的MySQL驱动程序是MySQL Connector/Python和PyMySQL。以下是使用MySQL Connector/Python连接MySQL数据库的基本步骤:
1.安装MySQL Connector/Python:可以在官网下载安装包,也可以使用pip安装:
```
pip install mysql-connector-python
```
2.导入MySQL Connector/Python模块:
```python
import mysql.connector
```
3.连接MySQL数据库:
```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")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
6.关闭数据库连接:
```python
mydb.close()
```
以上是连接MySQL数据库的基本步骤,可以根据具体情况进行修改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)