python怎么连接数据库
时间: 2024-01-10 17:47:23 浏览: 11
Python可以使用各种数据库API来连接不同类型的数据库。以下是连接MySQL数据库的示例:
1. 安装MySQL驱动程序
在Python中连接MySQL数据库,需要安装MySQL驱动程序。可以使用pip安装MySQL驱动程序:
```
pip install mysql-connector-python
```
2. 导入MySQL驱动程序
在Python程序中导入MySQL驱动程序:
```
import mysql.connector
```
3. 连接MySQL数据库
使用MySQL驱动程序创建一个连接,需要指定MySQL数据库的主机名、用户名、密码、数据库名称等信息:
```
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 或者使用以下方式连接数据库
# mydb = mysql.connector.connect(
# host="localhost",
# user="username",
# password="password"
# )
# 创建一个数据库
# mycursor = mydb.cursor()
# mycursor.execute("CREATE DATABASE mydatabase")
```
4. 创建一个游标对象
使用游标对象执行SQL查询:
```
mycursor = mydb.cursor()
# 查询数据
mycursor.execute("SELECT * FROM customers")
# 获取查询结果
result = mycursor.fetchall()
# 遍历结果
for row in result:
print(row)
```
以上是连接MySQL数据库的基本步骤,具体的操作可以根据实际需求进行调整。