python连接数据库mysql
时间: 2023-10-13 13:16:08 浏览: 77
在Python中连接MySQL数据库需要使用MySQL官方提供的Python库`mysql-connector-python`,具体步骤如下:
1. 安装`mysql-connector-python`库
```python
pip install mysql-connector-python
```
2. 导入库
```python
import mysql.connector
```
3. 建立连接
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
```
其中,`host`为数据库所在的主机名或IP地址,`user`和`password`为数据库的用户名和密码。
4. 创建游标对象
```python
mycursor = mydb.cursor()
```
5. 执行SQL语句
```python
mycursor.execute("SELECT * FROM mytable")
result = mycursor.fetchall()
for row in result:
print(row)
```
上面的代码执行了一条查询语句,将查询结果保存到`result`变量中,并逐行打印查询结果。
6. 关闭连接
```python
mydb.close()
```
完整代码示例:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM mytable")
result = mycursor.fetchall()
for row in result:
print(row)
mydb.close()
```
阅读全文