2、查 fetchone,fetchmany,fetchall
1、增、删、改
#安装 pip3 install pymysql
import pymysql #链接 conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') #游标 cursor=conn.cursor() #part1 # sql='insert into userinfo(name,password) values(%s,%s);' # res=cursor.execute(sql,("root","123456")) #执行sql语句,返回sql影响成功的行数 # print(res) #part2 sql='insert into userinfo(name,password) values(%s,%s);' res=cursor.executemany(sql,[("root","123456"),("lhf","12356"),("eee","156")]) #执行sql语句,返回sql影响成功的行数 print(res) conn.commit() #提交后才发现表中插入记录成功 cursor.close() conn.close()
2、查 fetchone,fetchmany,fetchall
import pymysql #链接 conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') #游标 cursor=conn.cursor() #执行sql语句 sql='select * from userinfo;' rows=cursor.execute(sql) #执行sql语句,返回sql影响成功的行数rows,将结果放入一个集合,等待被查询 # cursor.scroll(3,mode='absolute') # 相对绝对位置移动 # cursor.scroll(3,mode='relative') # 相对当前位置移动 res1=cursor.fetchone() res2=cursor.fetchone() res3=cursor.fetchone() res4=cursor.fetchmany(2) res5=cursor.fetchall() print(res1) print(res2) print(res3) print(res4) print(res5) print('%s rows in set (0.00 sec)' %rows) conn.commit() #提交后才发现表中插入记录成功 cursor.close() conn.close()
3、获取插入的最后一条数据的自增ID
import pymysql conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') cursor=conn.cursor() sql='insert into userinfo(name,password) values("xxx","123");' rows=cursor.execute(sql) print(cursor.lastrowid) #在插入语句后查看 conn.commit() cursor.close() conn.close()
4、封装pymsql
存储数据库信息application.yaml文件:
测试数据库: ############ 数据库 ############ host_name: '192.168.xx.xx' port: 3306 service_name: testdb username: 'root' password: '123456'
python代码封装:
import pymysql import os import sys import yaml sys.setrecursionlimit(10000) # 例如这里设置为一万 ''' 公共类''' class MyMysql(object): def __init__(self, db_path, db_name): ''' :param db_path: 获取数据库配置文件路径 :param db_name: 数据库名 ''' self.db_conf = self._get_yamlMsg(db_path).get(db_name) self.host = self.db_conf.get('host_name') self.port = self.db_conf.get('port') self.db = self.db_conf.get('service_name', None) self.username = self.db_conf.get('username') self.password = self.db_conf.get('password') def _get_yamlMsg(self, sql_path): ''' # open方法打开直接读出来 :return: ''' with open(sql_path, 'r', encoding='utf-8') as f: sqlMsg = f.read() # 用load方法转字典 sql_dic = yaml.load(sqlMsg) return sql_dic def get_connection(self): try: self.con = pymysql.Connect(host=self.host,port=self.port,user=self.username, passwd=self.password,db=self.db,charset='utf8') except Exception as e: print('连接数据库出错:', e) def get_cur(self): return self.con.cursor() def search(self, sql, data=None): ''' 查询 :param sql: :return: ''' try: cur = self.get_cur() cur.execute(sql) lines = cur.fetchall() except Exception as e: print('数据库查询出错:', e) cur.close() self.con_close() cur.close() return lines def excute(self, sql, data): ''' 插入、修改、删除 :param sql: :param data: [("root","123456"),("lhf","12356"),("eee","156")] :return: ''' try: cur = self.get_cur() # cur.execute('insert into user (name,password) value (?,?)', (name, password)) res = cur.executemany(sql, data) self.con.commit() # 提交except Exception as e: cur.close() self.con_close() print('数据库查询出错:', e) cur.close() return effectRow def con_close(self): self.con.close() if __name__ == '__main__': # 获取数据库配置文件路径 db_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'conf', "application.yaml") db = MyMysql(db_path, '测试数据库') db.get_connection() print(db.search('''select 1 from dual''')) db.con_close()