• Python 数据库操作 -- Mysql 数据库


    Python DB API

    价值

    Python访问数据库的统一接口规范,开发者不必再去针对不同数据库实现不同API

    官网

    https://www.python.org/dev/peps/pep-0249/

    内容

     

    使用流程

     

    开发环境搭建

    环境

             Python代码开发(Sublime Text3 / Notepad ++)

             Python客户端 AND Python-MySQL connector

             Mysql服务器(Mysql5.7 AND Navicat)

    安装Python-MySQL connector及遇到的问题

    安装

    win cmd 中输入 easy_install MySQL-python    或者     pip install MySQL-python

    Linux apt-get install python-dev    或者     yum install python-devel

    最笨的方法,到http://www.cr173.com/soft/22957.html这里下载了MySQL-python.rar安装包进行安装。

    问题

    Microsoft Visual C++ 9.0 is required  (Unable to find vcvarsall.bat)

             http://www.cnblogs.com/lemonlemontree/p/6921333.html

    Cannot open include file: 'config-win.h': No such file or directory

             http://www.cnblogs.com/dadadechengzi/p/6131799.html

             site.cfg需要下载MySQL-python的源代码包

    导入Python-MySQL完成

    >>> import MySQLdb

    >>> print MySQLdb

    <module 'MySQLdb' from 'C:Python27libsite-packagesmysql_python-1.2.5-py2.7-win-amd64.eggMySQLdb\__init__.pyc'>

    数据库连接对象--connection

    作用

    建立Python客户端与数据库的网络连接

    创建方法

    实例名=Mysqldb.connect(参数)

             host--字符串--mysql服务器地址

             port--数字--mysql服务器端口号

             user--字符串--用户名

             passwd--字符串--密码

             db--字符串--数据库名

             charset--字符串--连接编码

    实例方法

    cursor()--使用该链接创建并返回游标

    commit()--提交当前事务

    rollback()--回滚当前事务

    close()--关闭连接

    数据库游标对象--cursor

    作用

    用于执行查询和获取结果

    实例方法

    execute(op[,args])--执行一个数据库查询和命令

     

    fetchone()--获取下一行数据

    fetchmany(size)--获取下size行数据

    fetchall()--获取剩下的所有行(可直接使用for xx in cursor实例 来对cursor实例进行迭代

     

    rowcount--最近一次execute返回数据的行数或影响的行数,请注意,它是属性。

    rownumber--下一次使用fetchxxx时的index

    close()--关闭游标

    Python之Select查询操作

    理念

     

    实例:

     1 >>> import MySQLdb
     2 
     3 >>> test_conn=MySQLdb.Connect(host='127.0.0.1',port=3306,user='yc',passwd='Yc_123456',db='st',charset='utf8')
     4 
     5 >>> sql = "select * from student"
     6 
     7 >>> test_cursor=test_conn.cursor()
     8 
     9 >>> test_cursor.execute(sql)
    10 
    11 6L
    12 
    13 >>> test_cursor
    14 
    15 <MySQLdb.cursors.Cursor object at 0x0000000002EB7710>
    16 
    17 >>> test_rs=test_cursor.fetchall()
    18 
    19 >>> for row in test_rs:
    20 
    21 ...    print row
    22 
    23 ...
    24 
    25 (u'201215121', u'u674eu52c7', u'u7537', 21, u'CS')
    26 
    27 (u'201215122', u'u5218u6668', u'u5973', 23, u'CS')
    28 
    29 (u'201215123', u'u738bu654f', u'u5973', 19, u'MA')
    30 
    31 (u'201215125', u'u5f20u7acb', u'u7537', 20, u'IS')
    32 
    33 (u'201215126', u'u5f20u6210u6c11', u'u7537', 19, u'CS')
    34 
    35 (u'201215128', u'u9648u51ac', u'u7537', 19, u'IS')
    36 
    37 >>> for row in test_cursor:
    38 
    39 ...    print row
    40 
    41 ...
    42 
    43 (u'201215121', u'u674eu52c7', u'u7537', 21, u'CS')
    44 
    45 (u'201215122', u'u5218u6668', u'u5973', 23, u'CS')
    46 
    47 (u'201215123', u'u738bu654f', u'u5973', 19, u'MA')
    48 
    49 (u'201215125', u'u5f20u7acb', u'u7537', 20, u'IS')
    50 
    51 (u'201215126', u'u5f20u6210u6c11', u'u7537', 19, u'CS')
    52 
    53 (u'201215128', u'u9648u51ac', u'u7537', 19, u'IS')
    54 
    55 >>> test_cursor.fetchall()
    56 
    57 ()
    58 
    59 >>> test_cursor.rowcount
    60 
    61 6L
    62 
    63 >>> dir(test_cursor)
    64 
    65 ['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_executed', '_defer_warnings', '_do_get_result', '_do_query', '_executed', '_fetch_row', '_fetch_type', '_get_db', '_get_result', '_info', '_last_executed', '_post_get_result', '_query', '_result', '_rows', '_warning_check', '_warnings', 'arraysize', 'callproc', 'close', 'connection', 'description', 'description_flags', 'errorhandler', 'execute', 'executemany', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'messages', 'nextset', 'rowcount', 'rownumber', 'scroll', 'setinputsizes', 'setoutputsizes']
    66 
    67 >>> test_cursor.rownumber
    68 
    69 6
    70 
    71 >>> test_cursor.rownumber=0
    72 
    73 >>> test_cursor.fetchone()
    74 
    75 (u'201215121', u'u674eu52c7', u'u7537', 21, u'CS')
    76 
    77 >>> test_cursor.close()
    78 
    79 >>> test_conn.close()
    Python之Select查询简单举例

    Python之insert/update/delete更新操作&事务使用

    理念

     

    Python之事务的使用

    1.关闭自动提交:设置connection.autocommit(False)

    2.正常提交事务:connection.commit()

    3.异常回滚事务:connection.rollback()

    实例

     1 >>> import MySQLdb
     2 
     3 >>> test_conn=MySQLdb.Connect(host='127.0.0.1',port=3306,user='yc',passwd='Yc_123456',db='st',charset='utf8')
     4 
     5 >>> insert_sql="insert into student(Sno,Sname,Ssex,Sage,Sdept) values(201215130,'王晓东','男',18,'CS')"
     6 
     7 >>> update_sql="update student set Ssex='女' where Sno=201215130"
     8 
     9 >>> test_conn.autocommit(False)
    10 
    11 >>> test_cursor=test_conn.cursor()
    12 
    13 >>> try:
    14 
    15 ...    test_cursor.execute(insert_sql)
    16 
    17 ...    test_cursor.execute(update_sql)
    18 
    19 ...    test_conn.commit()
    20 
    21 ... except Exception as e:
    22 
    23 ...    print e
    24 
    25 ...    test_conn.rollback()
    26 
    27 ...
    28 
    29 1L
    30 
    31 1L
    32 
    33 >>> test_cursor.close()
    34 
    35 >>> test_conn.close()
    Python之更新语句简单举例

    注:

    (1062, "Duplicate entry '201215130' for key 'PRIMARY'")

    明明数据库中没有,但是爆了这个错,是因为crusor中已经有了'201215130'这个ID的记录,所以需要初始化cursor实例(先close(),在重新赋值)

    实例--银行转帐

     

    create table account (

    acctid INT(11) PRIMARY KEY COMMENT '账户ID',

    money NUMERIC(11,2) DEFAULT 0.00 COMMENT '余额'

    ) ENGINE = INNODB DEFAULT CHARSET = utf8;

    引擎选择--INNODB支持事务,MyISAM不支持事务

      1 # -*- coding:utf-8 -*-
      2 
      3 # 代码编写思路:先抽象后具体;先写框架,后写实现。
      4 # 1.获得源帐号、目标账号、转账金额
      5 # 2.连接数据库
      6 # 3.开始事务
      7 # 4.提交或回滚
      8 # *********************
      9 # 下列动作可封装到一个类中
     10 #   3.1检查源帐号是否可用
     11 #   3.2检查目标账号是否可用
     12 #   3.3检查源帐号是否有足够的钱
     13 #   3.4源帐号扣款
     14 #   3.5目标账号加钱
     15 
     16 
     17 import MySQLdb
     18 
     19 # parameters define here
     20 src_id = input('input src account id >')
     21 des_id = input('input des account id >')
     22 money = input('money number >')
     23 
     24 class MyException(Exception):
     25     def __init__(self,message):
     26         Exception.__init__(self)
     27         self.message=message   
     28 
     29 class TransferMoney(object):
     30     def __init__(self,db_connect_instance):
     31         self.__db_conn=db_connect_instance
     32 
     33     def check_account_available(self,account_id):
     34         print "检查账户%s是否可用..." % account_id
     35         __sql="select * from account where acctid=%s" % account_id
     36         __curosr = self.__db_conn.cursor()
     37         __curosr.execute(__sql)
     38         #print "rowcount-->%s" % __curosr.rowcount
     39         if __curosr.rowcount!=1:
     40             print "账户%s不可用"% account_id
     41             raise MyException("账户%s不可用"% account_id)
     42         print "账户%s可用" % account_id
     43         __curosr.close()
     44 
     45     def check_enough_money(self,account_id, money):
     46         print "检查账户%s余额是否足够..." % account_id
     47         __sql="select * from account where acctid=%s and money>=%s" % (account_id, money)
     48         __curosr = self.__db_conn.cursor()
     49         __curosr.execute(__sql)
     50         #print "rowcount-->%s" % __curosr.rowcount
     51         if __curosr.rowcount!=1:
     52             print "账户%s余额不足"% account_id
     53             raise MyException("账户%s余额不足"% account_id)
     54         print "账户%s余额充足" % account_id
     55         __curosr.close()
     56 
     57     def reduce_money(self,account_id, money):
     58         print "账户%s开始扣款..." % account_id
     59         __sql="update account set money=money-%s where acctid=%s" % (money, account_id)
     60         __curosr = self.__db_conn.cursor()
     61         __curosr.execute(__sql)
     62         #print "rowcount-->%s" % __curosr.rowcount
     63         if __curosr.rowcount!=1:
     64             print "账户%s扣款失败"% account_id
     65             raise MyException("账户%s扣款失败"% account_id)
     66         print "账户%s扣款成功" % account_id
     67         __curosr.close()
     68 
     69     def add_money(self,account_id, money):
     70         print "账户%s开始加钱..." % account_id
     71         __sql="update account set money=money+%s where acctid=%s" % (money, account_id)
     72         __curosr = self.__db_conn.cursor()
     73         __curosr.execute(__sql)
     74         #print "rowcount-->%s" % __curosr.rowcount
     75         if __curosr.rowcount!=1:
     76             print "账户%s加钱失败"% account_id
     77             raise MyException("账户%s加钱失败"% account_id)
     78         print "账户%s加钱成功" % account_id
     79         __curosr.close()
     80 
     81 def main():
     82     st_conn = MySQLdb.Connect(host='127.0.0.1',port=3306,user='yc',passwd='Yc_123456',db='st',charset='utf8')
     83 
     84     transfer_money = TransferMoney(st_conn)
     85 
     86     try:
     87         transfer_money.check_account_available(src_id)
     88         transfer_money.check_account_available(des_id)
     89         transfer_money.check_enough_money(src_id,money)
     90         transfer_money.reduce_money(src_id,money)
     91         transfer_money.add_money(des_id,money)
     92         st_conn.commit()
     93         print "从帐号%s转%s元到帐号%s成功!!!" % (src_id, money, des_id)
     94     except Exception as e:
     95         print "从帐号%s转%s元到帐号%s失败!!!" % (src_id, money, des_id)
     96         print e.message
     97         st_conn.rollback()
     98 
     99     st_conn.close()
    100 
    101 main()
    Python代码实现银行转帐
  • 相关阅读:
    文献阅读 | On the subspecific origin of the laboratory mouse
    文献阅读 | GenomicsDB: storing genome data as sparse columnar arrays.
    文献阅读 | The human Y chromosome: an evolutionary marker comes of age
    文献阅读 | HaploGrouper: A generalized approach to haplogroup classification
    文献阅读 | Systematic evaluation of error rates and causes in short samples in next-generation sequencing
    文献阅读 | The Wheat 660K SNP array demonstrates great potential for marker‐assisted selection in polyploid wheat
    使用HMM进行分类识别(以语音识别为例)
    文献阅读 | Fine definition of the pedigree haplotypes of closely related rice cultivars by means of genome-wide discovery of single-nucleotide polymorphisms
    GWAS学习笔记(一) | 质量控制(QC)
    python实现简单决策树(信息增益)——基于周志华的西瓜书数据
  • 原文地址:https://www.cnblogs.com/yc913344706/p/7805259.html
Copyright © 2020-2023  润新知