Python關於mySQL的串連外掛程式眾多,Bottle下也有人專門開發的外掛程式:bottle-mysql具體使用方法見官方,總共感覺其用法限制太多,其使用起來不方便,最適合的當然是,mySQL官網給Python提供的通用官方驅動,用起來很順手:mysql-connector 具體操作如下:
# -*- coding: utf-8 -*-#!/usr/bin/python# filename: login_admin.py# codedtime: 2014-9-7 11:26:11import bottleimport mysql.connector # 匯入mysql資料庫連接器def check_userinfo(): a_list = [] # 建立一個空列表 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() # 建立資料遊標 # 執行查詢 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_listdef 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 密碼為空白。