用python操作mysql資料庫(之代碼歸類)

來源:互聯網
上載者:User

標籤: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資料庫(之代碼歸類)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.