python 连接mysql数据库实现增删改查
时间: 2023-09-16 08:09:10 浏览: 64
连接MySQL数据库可以使用Python中的MySQLdb或者pymysql等库。以下是使用pymysql库实现增删改查的示例代码。
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8')
# 插入数据
def insert_data(name, age):
try:
cursor = conn.cursor()
sql = "INSERT INTO students(name, age) VALUES (%s, %s)"
cursor.execute(sql, (name, age))
conn.commit()
print('插入成功')
except Exception as e:
conn.rollback()
print('插入失败', e)
finally:
cursor.close()
# 删除数据
def delete_data(id):
try:
cursor = conn.cursor()
sql = "DELETE FROM students WHERE id = %s"
cursor.execute(sql, id)
conn.commit()
print('删除成功')
except Exception as e:
conn.rollback()
print('删除失败', e)
finally:
cursor.close()
# 更新数据
def update_data(id, age):
try:
cursor = conn.cursor()
sql = "UPDATE students SET age = %s WHERE id = %s"
cursor.execute(sql, (age, id))
conn.commit()
print('更新成功')
except Exception as e:
conn.rollback()
print('更新失败', e)
finally:
cursor.close()
# 查询数据
def query_data(name):
try:
cursor = conn.cursor()
sql = "SELECT * FROM students WHERE name = %s"
cursor.execute(sql, name)
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
age = row[2]
print(f'id={id}, name={name}, age={age}')
except Exception as e:
print('查询失败', e)
finally:
cursor.close()
if __name__ == '__main__':
insert_data('张三', 20)
delete_data(1)
update_data(2, 22)
query_data('张三')
# 关闭连接
conn.close()
```
以上代码连接到名为test的MySQL数据库中,对students表进行增删改查操作。其中,增加数据使用INSERT语句,删除数据使用DELETE语句,更新数据使用UPDATE语句,查询数据使用SELECT语句。使用try-except-finally结构确保代码执行过程中出现异常时能够及时关闭游标对象,回滚或提交事务,并关闭数据库连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)