mysql怎么连接python
时间: 2024-10-27 13:05:47 浏览: 6
python连接mysql8 数据入库
在Python中连接MySQL数据库通常通过使用名为`mysql-connector-python`或`pymysql`的第三方库。以下是简单的步骤:
1. 安装所需库:
使用pip安装:
```
pip install mysql-connector-python
# 或者如果是最新版本,可以安装pymysql:
pip install pymysql
```
2. 导入模块:
```python
import mysql.connector
```
3. 创建连接:
```python
# 配置数据库连接信息
connection = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="your_database"
)
```
4. 打开游标(Cursor)进行操作:
```python
cursor = connection.cursor()
```
5. 执行SQL查询或操作:
```python
query = "SELECT * FROM your_table;"
cursor.execute(query)
# 获取结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
connection.close()
```
阅读全文