安装方法:pip install pymysql
import pymysql # 建立数据库连接 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='111111', # passwd也可以 db='school', charset='utf8') # 如果查询有中文需要指定数据库编码 # 从连接建立游标,有了游标才能操作数据库 cur = conn.cursor() # 更改数据库 cur.execute("INSERT INTO student VALUES ( 777, 'hello.殷', '男', 1990, '历史', '湖南宁乡' )") # 查询数据库 cur.execute("select * from student where name='hello.殷'") # 获取查询结果 result = cur.fetchall() print(result) # 提交更改 conn.commit()
执行结果:
C:\Users\yzp\AppData\Local\Programs\Python\Python37\python.exe D:/00test/RFTEST/mysql.py ((777, 'hello.殷', '男', 1990, '历史', '湖南宁乡'),) Process finished with exit code 0什么是游标? 游标类似文件句柄,可以逐条的访问数据库执行结果集。pymysql中只能通过游标来执行sql和获取结果
使用cur.execute(), 执行数据库查询后无返回的是影响的行数,而非查询结果。我们要使用cur.fetchone()/cur.fetchmany()/cur.fetchall()来获取查询结果。
cur.execute(select * from user where name='张三') print(cur.fetchone()) # 结果: ('张三','123456') print(cur.fetchone()) # 结果:None print(cur.fetchall()) # 结果:()
所以我们需要重复使用查询结果时,需要将查询结果赋给某个变量
cur.execute(select * from user where name='张三') result = cur.fetchall() print(result) # 结果: ('张三','123456') print(result) # 结果: ('张三','123456')
try: cur.execute("insert into user (name,password) values ('张三', '123456')") cur.execute("insert into user (name, passwd) values ('李四'), '123456'") # 此处sql出错 conn.commit() # 使用连接提交所有更改 except Exception as e: conn.rollback() # 回滚所有更改(注意用的是conn) print(str(e))
import pymysql class DB: def __init__(self): self.conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='111111', db='school' ) self.cur = self.conn.cursor() def __del__(self): # 析构函数,实例删除时触发 self.cur.close() self.conn.close() def query(self, sql): # 查询函数 self.cur.execute(sql) return self.cur.fetchall() def exc(self, sql): # 执行函数 try: self.cur.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print(str(e)) def check(self, name): result = self.query("select * from student where name='{}'".format(name)) return True if result else False def del_user(self, name): self.exc("delete from student where name='{}'".format(name))
使用方法:
from db import * if check_user("张三"): del_user("张三")import pymysql class DB: def __init__(self): self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='111111', # passwd 不是 password db='scholl') self.cur = self.conn.cursor() def __del__(self): # 析构函数,实例删除时触发 self.cur.close() self.conn.close() def query(self, sql): self.cur.execute(sql) return self.cur.fetchall() def exec(self, sql): try: self.cur.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print(str(e)) def check_user(self, name): result = self.query("select * from user where name='{}'".format(name)) return True if result else False def del_user(self, name): self.exec("del from user where name='{}'".format(name))
使用方法:
from db2 import DB: db = DB() # 实例化一个数据库操作对象 if db.check_user("张三"): db.del_user("张三")