簡單的連接MySQL與Python的Bottle框架的方法
Python關于mySQL的連接插件眾多,Bottle下也有人專門開發(fā)的插件:bottle-mysql具體使用方法見官方,總共感覺其用法限制太多,其使用起來不方便,最適合的當然是,mySQL官網給Python提供的通用官方驅動,用起來很順手:mysql-connector 具體操作如下:
# -*- coding: utf-8 -*- #!/usr/bin/python # filename: login_admin.py # codedtime: 2014-9-7 11:26:11 import bottle import mysql.connector # 導入mysql數據庫連接器 def check_userinfo(): a_list = [] # 創(chuàng)建一個空列表 username = bottle.request.GET.get('loginname','').strip() # 用戶名 password = bottle.request.GET.get('password','').strip() # 密碼 if username is not None or password is not None: try: # 連接數據庫 conn = mysql.connector.connect(user='root', password='123456', database='myblog') cursor = conn.cursor() # 創(chuàng)建數據游標 # 執(zhí)行查詢 query = ("SELECT username, password FROM mb_users " "WHERE username=%s and password=%s") cursor.execute(query, (username, password)) a_list = cursor.fetchall() # fetchone獲取一個元組 #count = int(cursor.rowcount) # 獲取元組個數 return a_list except mysql.connector.Error as err: print("Something went wrong: {}".format(err)) exit() finally: conn.commit() # 提交修改 cursor.close() # 關閉數據庫 conn.close() else: return a_list def login_admin(): if bottle.request.GET.get('bs-submit','').strip(): #點擊登錄按鈕 a_list = check_userinfo() if a_list: a_name = a_list[0][0] # 獲得用戶名 return bottle.template('templates/index_user.tpl', username = a_name) else: return bottle.template('templates/login_admin.tpl', action='/login_admin', error_info='請輸入正確的用戶名或密碼!') else: return bottle.template('templates/login_admin.tpl', action='', error_info=' ')
以上是MySQL在Botlle中的簡單用法,
順便提一下:安裝和管理mySQL,建議安裝使用XAMPP,XAMPP集成了Apache, MySQL、PHP、Tomcat等多種工具,一次性解決安裝,不用自己繁瑣的一個個安裝和配置,而且管理也很方便。XAMPP安裝的MySQL默認用戶是:root 密碼為空。
相關文章
在Django中創(chuàng)建第一個靜態(tài)視圖
這篇文章主要介紹了在Django中創(chuàng)建第一個靜態(tài)視圖的方法,與其他編程語言的開始一樣,以Hello world作為示例,需要的朋友可以參考下2015-07-07python如何使用正則表達式的前向、后向搜索及前向搜索否定模式詳解
這篇文章主要給大家介紹了關于python如何使用正則表達式的前向、后向搜索及前向搜索否定模式的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-11-11