mysql和python连接方式
时间: 2023-09-03 15:06:19 浏览: 52
您可以使用Python中的MySQL Connector来连接MySQL数据库。首先,您需要确保已经安装了MySQL Connector模块,可以通过以下命令来安装:
```
pip install mysql-connector-python
```
然后,您可以使用以下代码示例来连接MySQL数据库:
```python
import mysql.connector
# 建立数据库连接
cnx = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="yourusername", # 数据库用户名
password="yourpassword", # 数据库密码
database="yourdatabase" # 数据库名称
)
# 创建一个游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM yourtable"
cursor.execute(query)
# 获取查询结果
result = cursor.fetchall()
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
```
在上面的示例中,您需要将`localhost`替换为您的数据库主机地址,`yourusername`和`yourpassword`替换为您的数据库用户名和密码,以及`yourdatabase`和`yourtable`替换为您要连接的数据库和表的名称。
这样,您就可以使用Python连接到MySQL数据库并执行查询操作了。