Python数据库操作

Python DB API

Python 访问数据库的统一接口程序

  • 数据库连接对象 - connection
  • 数据库交互对象 - cursor
  • 数据库异常对象 - exceptions

Python mysql 开发环境

  • 需要安装mysqldb 模块

mysql数据库连接对象connection

import Mysqldb

conn = Mysqldb.Connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = '123456',
        db = 'ewanreton'
        charset = 'utf-8'
        )
cursor = conn.cursor()
print conn
print cursor

cursor.close()
conn.close()
  • cursor 对象支持的方法
    • excute(op,[args]) 执行sql语句
    • fetchone() 获取结果集的下一条
    • fetchmany(size) 获取结果集的下几条
    • fetchall() 获取结果集剩下的所有行
    • rowcount 返回execute的行数
    • close()

使用select查询数据

import Mysqldb
conn = Mysqldb.Connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = '123456',
        db = 'ewanreton'
        charset = 'utf-8'
        )
cursor = conn.cursor()
sql = "select * from user"
cursor.execute(sql)
#print cursor.rowcount
#rs = cursor.fetchone()
#print rs
#rs = cursor.fetchmany(3)
#print rs
#re = cursor.fetchall()

rs = cursor.fetchall()
for row in rs:
    print "userid = %s,username= %s" % row
cursor.close()
conn.close()

insert/update/delete

import Mysqldb
conn = Mysqldb.Connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = '123456',
        db = 'ewanreton'
        charset = 'utf-8'
        )
cursor = conn.cursor()
sql_insert = "insert into user(userid,username) values (10,'name10')"
sql_update = "update user set username= 'name91' where userid=9"
sql_delete = "delete from user where userid<3"
try:
    cursor.execute(sql_insert)
    print cursor.rowcount
    cursor.execute(sql_update)
    print cursor.rowcount
    cursor.execute(sql_delete)
    print cursor.rowcount
    conn.commit()//需要提交事务,默认是关闭的
except Exception as e:
    print e
    conn.rollback()
cursor.close()
conn.close()

转账实例

#coding:utf8
import sys
import Mysqldb

class TransferMoney(object):
    def __init__(self,conn):
        self.conn = conn
    def check_acct_available(self,acctid):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account where acctid = %s" % acctid
            cursor.execute(sql)
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("账号%s不存在" %s acctid)
        finally:
            cursor.close()
    def has_enouth_money(self,money):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account where acctid = %s and money > %s" % (acctid,money) 
            cursor.execute(sql)
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("账号%s没有足够的钱" %s acctid)
        finally:
            cursor.close()
    def reduce_money(self,acctid,money):
        cursor = self.conn.cursor()
        try:
            sql = "update  account set money = money-%s where acctid = %s  > %s" % (money,acctid) 
            cursor.execute(sql)
            rs = cursor.rowcount()
            if len(rs) != 1:
                raise Exception("账号%s扣钱失败" %s acctid)
        finally:
            cursor.close()
    def add_money(self,acctid,money):
    cursor = self.conn.cursor()
        try:
            sql = "update  account set money = money+%s where acctid = %s  > %s" % (money,acctid) 
            cursor.execute(sql)
            rs = cursor.rowcount()
            if len(rs) != 1:
                raise Exception("账号%s加钱失败" %s acctid)
        finally:
            cursor.close()
    def transfer(self,source_acctid,target_acctid,money):
        try:
            self.check_acct_available(source_acctid)
            self.check_acct_available(target_acctid)
            self.has_enouth_money(source_acctid,money)
            self.reduce_money(source_acctid,money)
            self.add_money(target_acctid,money)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise e
            
if __name__=="__main__":
    source_acctid = sys.argv[1]
    target_acctid = sys.argv[2]
    money = sys.argv[3]
    
    conn = Mysqldb.connetc(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = '123456',
        db = 'ewanreton'
        charset = 'utf-8'
    )
    
    tr_money = TransferMoney(conn)
    
    try:
        tr_money.transfer(source_acctid,target_acctid,money)
    except Exception as e:
        print e
    finally:
        conn.close()

你可能感兴趣的:(Python数据库操作)