Python怎么连上MySQL
时间 : 2023-08-03 20:34:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

在Python中连接MySQL数据库需要使用到一个叫做`mysql-connector-python`的第三方库。下面是连接MySQL数据库的步骤:

1. 安装`mysql-connector-python`库,可以使用pip命令进行安装:

```shell

pip install mysql-connector-python

2. 导入`mysql.connector`模块:

```python

import mysql.connector

3. 建立与MySQL数据库的连接:

```python

mydb = mysql.connector.connect(

host="localhost", # 数据库主机地址

user="username", # 数据库用户名

passwd="password", # 数据库密码

database="database" # 数据库名称

)

替换`host`、`user`、`passwd` 和 `database` 分别为你的MySQL服务器地址、用户名、密码和数据库名称。

4. 创建一个`cursor`对象,用于执行SQL语句:

```python

mycursor = mydb.cursor()

5. 执行SQL查询:

```python

mycursor.execute("SELECT * FROM table")

可以将`SELECT * FROM table`替换为你需要执行的具体查询语句。

6. 获取查询结果:

```python

result = mycursor.fetchall()

for row in result:

print(row)

7. 执行完SQL语句后,需要关闭数据库连接:

```python

mydb.close()

完整的代码示例如下所示:

```python

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="username",

passwd="password",

database="database"

)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM table")

result = mycursor.fetchall()

for row in result:

print(row)

mydb.close()

以上就是在Python中连接MySQL数据库的步骤,你可以根据具体的需求,执行不同的SQL语句进行数据库操作。