python处理mysql中的数据
时间: 2024-01-13 12:03:37 浏览: 38
Python可以使用MySQL官方提供的MySQL Connector/Python模块来处理MySQL中的数据。以下是一个简单的示例:
1. 安装MySQL Connector/Python
在终端中运行以下命令:
```
pip install mysql-connector-python
```
2. 连接MySQL数据库
```python
import mysql.connector
# 建立连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 获取游标
mycursor = mydb.cursor()
```
3. 执行SQL查询
```python
# SELECT查询
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# INSERT语句
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
# UPDATE语句
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
# DELETE语句
sql = "DELETE FROM customers WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
```
4. 关闭连接
```python
mydb.close()
```