簡單的串連MySQL與Python的Bottle架構的方法

來源:互聯網
上載者:User
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 密碼為空白。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.