python操作mysql数据库用MySQLdb模板,操作postgresql则用psycopg2模块
安装MySQLdb(用yum安装,好像只能与mysql5.1版本配合使用):
- yum install -y MySQL-python
安装完后,可用import MySQLdb来使用
下面先简介MySQLdb的各种方法
MySQLdb.connect():连接数据库,主要有以下参数:
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码。
unix_socket:指定mysql的socket路径,如:unix_socket='/var/mysql/mysql.sock'
创建连接:
- conn = MySQLdb.connect(user='root',passwd='111111',host='localhost',port=3306, unix_socket='/var/mysql/mysql.sock',charset='utf8')
释放连接:
释放连接时可以应用Connection类型对象的close方法。一般操作完数据库后,需要关闭连接
- conn.close()
Cursor(游标)对象:
执行SQL语句前要获得一个指定连接的Cursor对象,由Cursor对象执行SQL查询并获取结果。
获得Cursor对象的方法
- cur = conn.cursor()
关闭Cursor:
执行SQL结束后正常要关闭cursor对象
- cur.close()
查询,插入,更新、删除操作:
Cursor类型提供了execute方法用于执行SQL操作
- execute(query [,parameters])
query是一个SQL字符串,parameters是一个序列或映射,返回值是所影响的记录数
查询
cur.execute("select user,host from mysql.user)
cur.execute("select * from user where name = %s and age = %s", {'name':'drfdai', 'age'30})
这里和字符串的格式化操作类似,但不管参数是什么类型,都要用'%s'
获取结果
获取结果集有三种方法,fetchone、fetchall和fetchmany,返回结果是一个tuple对象,tuple中的每一个元素对应查询结果中的一条记录。
fetchone()返回结果集中的一条记录
fetchall()返回结果集中的所有记录
fetchmany([N])返回结果集中N条记录
插入、更新、删除
cur.execute("insert user (name, age) values(%s, %s)", ('drfdai', 20))
更新和删除的操作与更新、删除类似
除了execute,Cursor类还提供了executemany()方法
executemany(query [, parametersequence])
querey是一个查询字符串,parametersequence是一个参数序列。这一序列的每一项都是一个序列或映射象。但executemany只适合插入、更新或删除操作,而不适用于查询操作。
cur.execute("insert user(name, age) values(%s, %s)", (('drf', 31), ('jiang', 21)))
提交
mysql现在一般会默认InnoDB作为默认引擎,InnoDB引擎执行插入、更新、删除操作后要进行提交,才会更新数据库,因此需要用commit()提交后,才会生效执行的SQL
cur.commit()
回滚
如果在执行事务SQL时,需要回滚的话,就用以下rollback()
rollback()
对以上操作,进行一个简单的函数封装,这样用起来更方便,特别是需要经常读写数据库的时候,省事,以下是我封装好的简单函数:
- #!/usr/bin/env python
- #coding=utf-8
- import MySQLdb
- import logging
- #定义错误日志路径
- error_log = '/'.join((pro_path,'log/task_error.log'))
- #定义日志输出格式
- logging.basicConfig(level=logging.ERROR,
- format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
- datefmt = '%Y-%m-%d %H:%M:%S',
- filename = error_log,
- filemode = 'a')
- #定义数据库参数
- db_name = 'task'
- db_user = 'root'
- db_pass = '111111'
- db_ip = 'localhost'
- db_port = 3306
- def writeDb(sql,db_data=()):
- """
- 连接mysql数据库(写),并进行写的操作
- """
- try:
- conn = MySQLdb.connect(db=db_name,user=db_user,passwd=db_pass,host=db_ip,port=int(db_port))
- cursor = conn.cursor()
- except Exception,e:
- print e
- logging.error('数据库连接失败:%s' % e)
- return False
- try:
- cursor.execute(sql,db_data)
- conn.commit()
- except Exception,e:
- conn.rollback()
- logging.error('数据写入失败:%s' % e)
- return False
- finally:
- cursor.close()
- conn.close()
- return True
- def readDb(sql,db_data=()):
- """
- 连接mysql数据库(从),并进行数据查询
- """
- try:
- conn = MySQLdb.connect(db=db_name,user=db_user,passwd=db_pass,host=db_ip,port=int(db_port))
- cursor = conn.cursor()
- except Exception,e:
- print e
- logging.error('数据库连接失败:%s' % e)
- return False
- try:
- cursor.execute(sql,db_data)
- data = [dict((cursor.description[i][0], value) for i, value in enumerate(row)) for row in cursor.fetchall()]
- except Exception,e:
- logging.error('数据执行失败:%s' % e)
- return False
- finally:
- cursor.close()
- conn.close()
- return data
如果数据库连接失败,把错误写入日志,并返回Flase。
writeDb是用来写入数据的,如果写入失败,写会把错误写入服务器日志中,然后返回False,如果成功,返回True。
readDb是用来读取数据的,如果读取失败,写会把错误写入服务器日志中,然后返回False,如果成功,则返回查询到的数据,数据类型是经过处理好的字典格式。
以下是writeDb和readDb使用的方法:
- @route('/api/getuser',method="POST")
- def getuser():
- sql = "select * from user;"
- userlist = readDb(sql,)
- return json.dumps(userlist)
- @route('/adduser',method="POST")
- def adduser():
- name = request.forms.get("name")
- age = request.forms.get("age")
- sex = request.forms.get("sex")
- qq = request.forms.get("qq")
- email = request.forms.get("email")
- departmentid = request.forms.get("department")
- if not name or not age or not sex or not qq or not email or not departmentid:
- return '-2'
- sql = """
- INSERT INTO
- user(name,age,sex,qq,email,departmentid)
- VALUES(%s,%s,%s,%s,%s,%s)
- """
- data = (name,age,sex,qq,email,departmentid)
- result = writeDb(sql,data)
- if result:
- return '0'
- else:
- return '-1'
更多的功能,可以查看bottle官网文档或其它教程
官方文档:http://www.bottlepy.org/docs/dev/index.html
SVN请跳转至:python bottle框架(WEB开发、运维开发)教程目录>
这些代码已提交到SVN中,有需要的朋友可在SVN下载
来自外部的引用: 1