python访问数据库,,1. python


1. python DB api简介

python DB api python访问数据库的统一接口规范,详细可参考https://www.python.org/dev/peps/pep-0249/python DB api中主要包括三个重要的对象 数据库连接对象 connection,数据库交互对象 cursor和数据库异常类 exceptions

2. 使用python DB API访问数据库的流程

技术分享

3. python+MYSQL开发环境的配置

技术分享python-mysql connector 用于python和mysql服务器进行连接,下载地址 https://sourceforge.net/projects/mysql-python/syslog是一个Mysql可视化的管理工具, 下载地址 https://sqlyog.en.softonic.com/

4 connection对象

使用方法MySQLdb.connection(host,port,user,passwd,db,charset)返回一个connection对象

connection对象支持的方法有

方法说明
cursor()使用该连接创建并返回的游标
commit()提交当前事务
rollback()回滚当前事务
close()关闭连接


连接数据库

 1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3                           port = 3306, 4                           user = ‘root‘, 5                           passwd = ‘123456‘, 6                           db = ‘test‘, 7                           charset=‘utf8‘) 8 cur = conn.cursor() 9 cur.close()10 conn.close()

5. 数据库游标对象cursor

cursor对象的方法  execute(op[,args]) 执行一个数据库查询和命令  fetchone() 取得结果集中下一行  fetchmany(size) 获取结果集中下几行  fetchall() 获取结果集剩下的所有行  rowcount 最近一次execute返回的数据的行数或影响的行数  close() 关闭游标对象技术分享我们在数据库中建立了一个test数据库,在其中建立了一个user表如下图所示技术分享利用cursor对象来执行简单的查询语句
 1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3                           port = 3306, 4                           user = ‘root‘, 5                           passwd = ‘123456‘, 6                           db = ‘test‘, 7                           charset=‘utf8‘) 8 cur = conn.cursor() 9 sql = ‘select * from user‘10 cur.execute(sql)11 print cur.rowcount12 print cur.fetchone()13 print cur.fetchmany(3)14 print cur.fetchall()15 cur.close()16 conn.close()

输出

9 (1L, u‘name1‘) ((2L, u‘name2‘), (3L, u‘name3‘), (4L, u‘name4‘)) ((5L, u‘name5‘), (6L, u‘name6‘), (7L, u‘name7‘), (8L, u‘name8‘), (9L, u‘name9‘))技术分享6. 事务处理事务:访问和更新数据库的一个程序执行单元
原子性:事务中包括的诸操作要么都做,要么都不做一致性:事务必须使数据库从一致性状态变到另一个一致性状态隔离性:一个事务的执行不能被其他事务干扰持久性:事务一旦提交,它对数据库的改变是永久性的开发中怎样使用事务?关闭自动commit:设置conn.autocommit(False)正常结束事务:conn.commit()异常结束事务:conn.rollback()
代码示例
 1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3                           port = 3306, 4                           user = ‘root‘, 5                           passwd = ‘123456‘, 6                           db = ‘test‘, 7                           charset=‘utf8‘) 8 cur = conn.cursor() 9 sql_insert = "insert into user(usrid, usrname) values(10, ‘name10‘)"10 sql_delete = "delete from user where usrid<3"11 sql_update = "update user set usrname = ‘name91‘ where usrid=9"12 try:13     cur.execute(sql_insert)14     cur.execute(sql_update)15     cur.execute(sql_delete)16     conn.commit()17 except Exception as e:18     print e19     conn.rollback()20 cur.close()21 conn.close()

7. 银行转账实例

假设张三要向王五转账100元,其转账流程如下图所示

技术分享代码实现
 1 import MySQLdb 2 def checkAccountAvailable(conn,username): 3     cur = conn.cursor() 4     sql = "select * from account where username=‘%s‘"%username 5     print sql 6     cur.execute(sql) 7     r = cur.rowcount 8     print r 9     cur.close()10     return r11    12 def account(conn, username):13     cur=conn.cursor()14     sql = "select * from account where username=‘%s‘"%username15     print sql16     cur.execute(sql)17     account = cur.fetchone()[1]18     cur.close19     return  account20 def main():21     conn = MySQLdb.Connect(host = ‘127.0.0.1‘,22                           port = 3306,23                           user = ‘root‘,24                           passwd = ‘123456‘,25                           db = ‘test‘,26                           charset=‘utf8‘)27     if checkAccountAvailable(conn,‘zhangsan‘) and checkAccountAvailable(conn,‘wangwu‘):28         if account(conn,"zhangsan") >= 100:29             try:30                 cur = conn.cursor()31                 cur.execute("update account set account=account-100 where username=‘zhangsan‘")32                 cur.execute("update account set account=account+100 where username=‘wangwu‘")33                 conn.commit()34             except Exception as e:35                 print e36                 conn.rollback()37             finally:38                 cur.close()39         else:40             print "zhangsan has not enough money"41     else:42         print "account not existed"43         44     conn.close()45 main()








null



python访问数据库

评论关闭