educoder:MySQL常用操作python
时间: 2024-10-09 13:12:49 浏览: 46
Educoder: MySQL是一种广泛使用的开源关系型数据库管理系统,在Python中,我们可以利用`pymysql`或`mysql-connector-python`库来进行与MySQL的交互。以下是几个常用的Python操作MySQL的示例:
1. **连接数据库**:
```python
import pymysql
# 连接参数
host = 'localhost'
user = 'your_username'
password = 'your_password'
db = 'your_database'
# 创建连接
connection = pymysql.connect(host=host,
user=user,
password=password,
db=db)
```
2. **执行SQL查询**:
```python
cursor = connection.cursor()
query = "SELECT * FROM table_name"
cursor.execute(query)
# 获取结果
rows = cursor.fetchall()
for row in rows:
print(row)
```
3. **插入数据**:
```python
data = ('value1', 'value2')
insert_query = f"INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
cursor.execute(insert_query, data)
connection.commit() # 提交事务
```
4. **更新和删除记录**:
```python
update_query = "UPDATE table_name SET column1=%s WHERE condition"
cursor.execute(update_query, (new_value,))
delete_query = "DELETE FROM table_name WHERE condition"
cursor.execute(delete_query)
```
5. **关闭连接**:
```python
cursor.close()
connection.close()
```
阅读全文