简单的连接MySQL与Python的Bottle框架的方法
Python关于mySQL的连接插件众多,Bottle下也有人专门开发的插件:bottle-mysql具体使用方法见官方,总共感觉其用法限制太多,其使用起来不方便,最适合的当然是,mySQL官网给Python提供的通用官方驱动,用起来很顺手:mysql-connector 具体操作如下:
#-*-coding:utf-8-*- #!/usr/bin/python #filename:login_admin.py #codedtime:2014-9-711:26:11 importbottle importmysql.connector#导入mysql数据库连接器 defcheck_userinfo(): a_list=[]#创建一个空列表 username=bottle.request.GET.get('loginname','').strip()#用户名 password=bottle.request.GET.get('password','').strip()#密码 ifusernameisnotNoneorpasswordisnotNone: try: #连接数据库 conn=mysql.connector.connect(user='root',password='123456',database='myblog') cursor=conn.cursor()#创建数据游标 #执行查询 query=("SELECTusername,passwordFROMmb_users" "WHEREusername=%sandpassword=%s") cursor.execute(query,(username,password)) a_list=cursor.fetchall()#fetchone获取一个元组 #count=int(cursor.rowcount)#获取元组个数 returna_list exceptmysql.connector.Erroraserr: print("Somethingwentwrong:{}".format(err)) exit() finally: conn.commit()#提交修改 cursor.close()#关闭数据库 conn.close() else: returna_list deflogin_admin(): ifbottle.request.GET.get('bs-submit','').strip():#点击登录按钮 a_list=check_userinfo() ifa_list: a_name=a_list[0][0]#获得用户名 returnbottle.template('templates/index_user.tpl',username=a_name) else: returnbottle.template('templates/login_admin.tpl',action='/login_admin', error_info='请输入正确的用户名或密码!') else: returnbottle.template('templates/login_admin.tpl',action='',error_info='')
以上是MySQL在Botlle中的简单用法,
顺便提一下:安装和管理mySQL,建议安装使用XAMPP,XAMPP集成了Apache,MySQL、PHP、Tomcat等多种工具,一次性解决安装,不用自己繁琐的一个个安装和配置,而且管理也很方便。XAMPP安装的MySQL默认用户是:root 密码为空。