一: 安装pymysql
pip3 install pymysql
二: 查询操作
import pymysql# 打开数据库连接db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306)# 使用cursor()方法获取操作游标cur = db.cursor()#1, 查询操作# 编写sql,查询语句 s_info 对应的表名sql = "select * from s_info"try: cur.execute(sql) # 执行sql语句 # results = cur.fetchall() # 获取一行 # result_one = cur.fetchone() # print(result_one) # 获取多个 result_many = cur.fetchmany(3) print(result_many) # print(results) # 返回所有的数据一元组套元组的形式 # print("id", "name", "pwd") # #遍历结果 # for row in results: # id = row[0] # name = row[1] # password = row[2] # print(id, name, password)except Exception as e: raise efinally: db.close()
三: 插入操作
import pymysql#2 插入操作db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo')# 使用游标cur = db.cursor()sql_insert = "insert into s_info(name, pwd) values('egon', '456')"try: cur.execute(sql_insert) db.commit()except Exception as e: db.rollback() raise efinally: cur.close() db.close()
四: 修改操作
import pymysql# 获取数据库db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306)# 获取游标cur = db.cursor()# sql改语句sql = "update s_info set name=%s where id=7"try: cur.execute(sql, "egon") db.commit()except Exception as e: raise efinally: cur.close() db.close()
五: 删除操作
import pymysqldb = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo')cur = db.cursor()sql = "delete from s_info where id=1"try: cur.execute(sql) db.commit()except Exception as e: raise efinally: cur.close() db.close()