用python连接mysql
时间: 2023-08-04 12:12:23 浏览: 39
可以使用Python中的`mysql-connector-python`模块来连接MySQL数据库。以下是一个简单的示例:
首先需要安装`mysql-connector-python`模块,可以使用以下命令来安装:
```
pip install mysql-connector-python
```
连接MySQL数据库的示例代码如下:
```python
import mysql.connector
# 连接MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建一个游标对象
mycursor = mydb.cursor()
# 执行SQL查询语句
mycursor.execute("SELECT * FROM customers")
# 获取查询结果
myresult = mycursor.fetchall()
# 输出查询结果
for x in myresult:
print(x)
```
在上面的代码中,我们首先使用`mysql.connector.connect()`函数来连接MySQL数据库,然后使用`cursor()`方法创建一个游标对象,然后使用`execute()`方法来执行SQL查询语句,最后使用`fetchall()`方法获取查询结果。
需要注意的是,如果要执行写入或更新操作,需要使用`commit()`方法来提交更改。
```python
# 执行SQL写入语句
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# 提交更改
mydb.commit()
```