python中MySQL库的连接
时间: 2024-10-20 10:02:30 浏览: 40
在Python中,要使用MySQL数据库,通常我们会选择`pymysql`或更推荐的`mysql-connector-python`库。以下是简单的连接步骤:
首先,你需要安装相应的库,可以使用pip命令:
```bash
pip install mysql-connector-python
```
然后,在Python代码中建立连接的基本语法如下:
```python
import mysql.connector
# 创建连接对象
cnx = mysql.connector.connect(
host="你的主机地址",
user="你的用户名",
password="你的密码",
database="你的数据库名称"
)
# 检查连接是否成功
if cnx.is_connected():
print(f"已成功连接到MySQL服务器: {cnx.get_server_info()}")
try:
# 执行SQL查询、插入等操作
cursor = cnx.cursor()
sql_query = "SELECT * FROM table_name"
cursor.execute(sql_query)
results = cursor.fetchall()
for row in results:
print(row)
finally:
# 关闭游标和连接
cursor.close()
cnx.close()
```
在这段代码里,你需要将`host`、`user`、`password`和`database`替换为你实际的MySQL服务器信息。
阅读全文
相关推荐

















