pymysql 对数据库进行增删查改
时间: 2023-11-07 14:01:02 浏览: 117
对数据库的增删查改
Pymysql 是 Python 语言下操作 MySQL 数据库的库,可以通过它来进行增删查改等操作。
以下是针对 pymysql 进行增删查改的示例代码:
1. 建立连接
```python
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
```
2. 插入数据
```python
cursor = conn.cursor()
sql = "INSERT INTO table_name (column1, column2, column3) VALUES (%s, %s, %s)"
val = ("value1", "value2", "value3")
cursor.execute(sql, val)
conn.commit()
```
3. 查询数据
```python
cursor = conn.cursor()
sql = "SELECT * FROM table_name WHERE column1 = %s"
val = ("value1", )
cursor.execute(sql, val)
result = cursor.fetchall()
for row in result:
print(row)
```
4. 更新数据
```python
cursor = conn.cursor()
sql = "UPDATE table_name SET column1 = %s WHERE column2 = %s"
val = ("new_value1", "value2")
cursor.execute(sql, val)
conn.commit()
```
5. 删除数据
```python
cursor = conn.cursor()
sql = "DELETE FROM table_name WHERE column1 = %s"
val = ("value1", )
cursor.execute(sql, val)
conn.commit()
```
注意:在使用完 pymysql 后需要关闭连接,以释放资源。
```python
conn.close()
```
阅读全文