码迷,mamicode.com
首页 > 数据库 > 详细

python访问数据库

时间:2017-05-23 12:19:43      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:bsp   fetch   处理   project   ffffff   dev   user   数据库   org   

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.rowcount
12 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 e
19     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 r
11    
12 def account(conn, username):
13     cur=conn.cursor()
14     sql = "select * from account where username=‘%s‘"%username
15     print sql
16     cur.execute(sql)
17     account = cur.fetchone()[1]
18     cur.close
19     return  account
20 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 e
36                 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()

 

 
 
 
 

 

 

 
 

 

 

 

 

 

 

 
 
 





python访问数据库

标签:bsp   fetch   处理   project   ffffff   dev   user   数据库   org   

原文地址:http://www.cnblogs.com/blackclody/p/6893235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!