python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

时间:2023-03-09 03:08:46
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

1.通过 pip 安装 pymysql

进入 cmd  输入  pip install pymysql  
回车等待安装完成;
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
安装完成后出现如图相关信息,表示安装成功。

2.测试连接

import pymysql  #导入 pymysql ,如果编译未出错,即表示 pymysql 安装成功

简单的增删改查操作

示例表结构
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

2.1查询操作

  1. import pymysql  #导入 pymysql
  2. #打开数据库连接
  3. db= pymysql.connect(host="localhost",user="root",
  4. password="123456",db="test",port=3307)
  5. # 使用cursor()方法获取操作游标
  6. cur = db.cursor()
  7. #1.查询操作
  8. # 编写sql 查询语句  user 对应我的表名
  9. sql = "select * from user"
  10. try:
  11. cur.execute(sql)    #执行sql语句
  12. results = cur.fetchall()    #获取查询的所有记录
  13. print("id","name","password")
  14. #遍历结果
  15. for row in results :
  16. id = row[0]
  17. name = row[1]
  18. password = row[2]
  19. print(id,name,password)
  20. except Exception as e:
  21. raise e
  22. finally:
  23. db.close()  #关闭连接

2.2插入操作

  1. import pymysql
  2. #2.插入操作
  3. db= pymysql.connect(host="localhost",user="root",
  4. password="123456",db="test",port=3307)
  5. # 使用cursor()方法获取操作游标
  6. cur = db.cursor()
  7. sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""
  8. try:
  9. cur.execute(sql_insert)
  10. #提交
  11. db.commit()
  12. except Exception as e:
  13. #错误回滚
  14. db.rollback()
  15. finally:
  16. db.close()

2.3更新操作

  1. import pymysql
  2. #3.更新操作
  3. db= pymysql.connect(host="localhost",user="root",
  4. password="123456",db="test",port=3307)
  5. # 使用cursor()方法获取操作游标
  6. cur = db.cursor()
  7. sql_update ="update user set username = '%s' where id = %d"
  8. try:
  9. cur.execute(sql_update % ("xiongda",3))  #像sql语句传递参数
  10. #提交
  11. db.commit()
  12. except Exception as e:
  13. #错误回滚
  14. db.rollback()
  15. finally:
  16. db.close()

2.4删除操作

  1. import pymysql
  2. #4.删除操作
  3. db= pymysql.connect(host="localhost",user="root",
  4. password="123456",db="test",port=3307)
  5. # 使用cursor()方法获取操作游标
  6. cur = db.cursor()
  7. sql_delete ="delete from user where id = %d"
  8. try:
  9. cur.execute(sql_delete % (3))  #像sql语句传递参数
  10. #提交
  11. db.commit()
  12. except Exception as e:
  13. #错误回滚
  14. db.rollback()
  15. finally:
  16. db.close()