python脚本中MySQL库使用pymysql连接
时间: 2024-10-17 11:10:43 浏览: 37
在Python中,要使用MySQL数据库,你可以通过`pymysql`库来建立连接。首先,你需要安装这个库,通常使用pip命令:
```bash
pip install pymysql
```
然后,在Python脚本中,连接MySQL数据库的基本步骤如下:
```python
import pymysql
# 数据库连接信息
db_config = {
'host': 'localhost', # 连接地址,默认为localhost
'user': 'your_username', # 用户名
'password': 'your_password', # 密码
'database': 'your_database', # 要连接的数据库名称
}
# 连接到MySQL
try:
connection = pymysql.connect(**db_config)
print("Connected to MySQL successfully")
except pymysql.Error as e:
print(f"Error connecting to MySQL: {e}")
# 创建一个游标对象用于执行SQL操作
cursor = connection.cursor()
# 执行查询、插入等操作...
# 示例:查询数据
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取结果并处理...
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
connection.close()
```
记得替换`your_username`、`your_password`和`your_database`为实际的数据库信息。
阅读全文
相关推荐


















