Python3 pymysql 訪問MySql數據庫
阿新 • • 發佈:2018-09-27
date char password ins limit 數據庫連接 cursor select comm
使用pymysql來訪問MySQL數據庫,註意,有些使用PyMySQL,Python2是mysqldb
如沒該module則安裝:pip install pymysql
(本人Java轉Python,還有java編寫習慣,有錯誤請及時提出,相互交流)
1、定義獲取數據庫連接的Module,
DataBase.py
import pymysql class MySQLDB: __config={ ‘host‘ : ‘127.0.0.1‘, ‘port‘ : 3306, ‘user‘ : ‘root‘, ‘password‘ : ‘admin‘,‘db‘ : ‘test‘, ‘charset‘ : ‘utf8‘ } #定義了靜態方法,類名可直接打點調用 @staticmethod def getConn(): connection = pymysql.connect(**MySQLDB.__config) return connection
2、EmpDao.py 訪問數據DAO層
1 from dataBase import DataBase 2 from dataBase import Entity 3 4 class EmpDao: 5 ‘‘‘6 emp表的DAO 7 ‘‘‘ 8 def saveEmp(self,empEntity): 9 """ 10 保存 11 """ 12 try: 13 self.connection=DataBase.MySQLDB.getConn();#獲取數據庫連接 14 with self.connection.cursor() as cursor: #獲取遊標 15 sql = ‘INSERT INTO emp (empno,ename,mgr,job,hiredate,sal,comm,deptno) VALUES (%s, %s, %s, %s, %s,%s,%s,%s)‘ 16 cursor.execute(sql, empEntity) #執行SQL 17 self.connection.commit() #提交事務 18 except Exception as e: 19 print(e) #打印異常 20 finally: 21 self.connection.close()#關閉數據庫連接 22 23 24 def selectEmp(self,sqlParam): 25 """ 26 條件查詢 27 """ 28 try: 29 self.connection = DataBase.MySQLDB.getConn(); 30 with self.connection.cursor() as cursor: 31 sql=‘select empno,ename,job,mgr,sal,comm,hiredate,deptno from emp where 1=1 ‘ 32 if sqlParam: 33 sql=sql+‘ %s ‘%(sqlParam) #插入條件sql片段 34 print(sql) 35 cursor.execute(sql) 36 self.rows = cursor.fetchall()#抓取行數據 37 except Exception as e: 38 print(e) 39 finally: 40 self.connection.close() 41 return self.rows 42 43 44 def selectRowCount(self,sqlParam): 45 """ 46 查詢總記錄數 47 """ 48 try: 49 self.connection=DataBase.MySQLDB.getConn() 50 with self.connection.cursor() as cursor: 51 sql=‘select count(empno) from emp where 1=1 ‘ 52 if sqlParam: 53 sql=sql+‘%s‘%(sqlParam)#sql條件片段 54 print(sql) 55 cursor.execute(sql) 56 self.rows=cursor.fetchall() 57 except Exception as e: 58 print(e) 59 finally: 60 self.connection.close() 61 return self.rows[0][0] 62 63 64 def selectRowsPaper(self,sqlParam=None,pageNow=1,pageSize=5): 65 """ 66 分頁查詢 67 """ 68 self.pageNow=pageNow 69 self.pageSize=pageSize 70 self.offset=(self.pageNow-1)*self.pageSize #偏移量 71 self.total=self.selectRowCount(sqlParam)#總記錄數 72 #總頁數 73 self.totalPage= int(self.total/self.pageSize) if self.total%self.pageSize==0 else int(self.total/self.pageSize) +1 74 75 try: 76 self.connection = DataBase.MySQLDB.getConn() 77 with self.connection.cursor() as cursor: 78 sql = ‘select empno,ename,job,mgr,sal,comm,hiredate,deptno from emp where 1=1 ‘ 79 if sqlParam: 80 sql = sql + ‘%s‘ % (sqlParam) 81 sql=sql+‘ limit %s,%s‘%(self.offset,self.pageSize) 82 print(sql) 83 cursor.execute(sql) 84 self.rows = cursor.fetchall() 85 return {‘total‘:self.total,‘pageNow‘:self.pageNow,‘totalPage‘:self.totalPage,‘rows‘:self.rows} 86 except Exception as e: 87 print(e)
3、測試
(1)新增
1 if __name__ == ‘__main__‘: 2 empDao =EmpDao() 3 empDao.saveEmp((116, ‘ZYG‘, 7989, ‘Teacher‘, ‘1999-10-10‘, 23000, None, 20))
(2)分頁查詢
if __name__ == ‘__main__‘: empDao =EmpDao() #分頁查詢 res=empDao.selectRowsPaper(pageNow=2) print(res) s=res[‘rows‘] for r in s: print(‘編號:%s,姓名:%s,入職日期:%s,工資:%s,部門:%s‘ % (r[0], r[1], r[6], r[4], r[7]))
Python3 pymysql 訪問MySql數據庫