標籤:python
650) this.width=650;" src="http://s2.51cto.com/wyfs02/M01/8A/C7/wKiom1g7x0ix4njuAAFB58eby5Y106.png-wh_500x0-wm_3-wmp_4-s_2227896382.png" title="QQ圖片20161128135645.png" alt="wKiom1g7x0ix4njuAAFB58eby5Y106.png-wh_50" />
index.py 這裡只是假設一個類比登陸
# -*- coding: utf-8 -*-"""Created on Sun Nov 27 18:54:29 2016這是主程式檔案@author: toby"""from model.user import Userdef main(): username = "tantianran1" user = User() result = user.Check_Username(username) if not result: print ‘使用者不存在,請重新登入‘ else: print ‘登入成功‘if __name__ == "__main__": main()
user.py
# -*- coding: utf-8 -*-"""Created on Sun Nov 27 19:48:03 2016對資料庫表的處理,py檔案名稱和表名一一對應所以,在這裡的user.py檔案是對資料庫表為user的處理@author: toby"""import syssys.path.append("/home/toby/workspace/date20161128")from utility.sql_helper import MysqlHelperclass User(object): def __init__(self): self.__helper = MysqlHelper() def Get_data_by_id(self,ids): sql = "select * from user where id=%s" params = (ids,) return self.__helper.Get_One_Data(sql,params) def Check_Username(self,name): sql = "select * from user where name=%s" params = (name,) return self.__helper.Get_One_Data(sql,params)‘‘‘a = User()print a.Check_Username(‘tantianran‘)‘‘‘
sql_helper.py
# -*- coding: utf-8 -*-"""Created on Sun Nov 27 18:57:44 2016資料處理層,處理資料的最底層,例如增刪改查的功能@author: toby"""import MySQLdbclass MysqlHelper(object): def __init__(self): hosts,users,password,dbname = ‘127.0.0.1‘,‘root‘,‘1qaz#EDC‘,‘test_db‘ self.conn = MySQLdb.connect(host=hosts,user=users,passwd=password,db=dbname) self.cur = self.conn.cursor(MySQLdb.cursors.DictCursor) def Get_Dict_data(self,sql,params): self.cur.execute(sql,params) data = self.cur.fetchall() #fetchall()擷取所有資料 self.cur.close() self.conn.close() return data def Get_One_Data(self,sql,params): self.cur.execute(sql,params) data = self.cur.fetchone() #fetchone()是擷取一條資料 self.cur.close() self.conn.close() return data
本文出自 “FA&IT營運-Q群:223843163” 部落格,請務必保留此出處http://freshair.blog.51cto.com/8272891/1877284
用python操作mysql資料庫(之代碼歸類)