• 3 Selenium Python 数据库及文件


    1 MySQL

    1.1 安装

    下载:MySQL-python-1.2.3.win-amd64-py2.7直接安装,要求Python2.7(Python version 2.7 required)

    验证:import MySQLdb 不报错就可以了

    1.2 基础

    1 连接数据库:MySQLdb.connect(host='',port='',user='',passwd='',db='')

    class Connection(_mysql.connection):

        """MySQL Database Connection Object"""

        default_cursor = cursors.Cursor
        
        def __init__(self, *args, **kwargs):
            """
            Create a connection to the database. It is strongly recommended
            that you only use keyword parameters. Consult the MySQL C API
            documentation for more information.
            host
              string, host to connect  
            user
              string, user to connect as
            passwd
              string, password to use
            db
              string, database to use
            port
              integer, TCP/IP port to connect to
            charset
              If supplied, the connection character set will be changed
              to this character set (MySQL-4.1 and newer). This implies
              use_unicode=True.
            """

    2 操作数据库:首先需要获得一个cursor对象, 然后使用cursor的方法执行SQL

    • execute(sql, args):执行单条sql语句,接收的参数为sql语句和参数列表,返回值为受影响的行数

        def execute(self, query, args=None):

            """Execute a query.
       
            query -- string, query to execute on server
            args -- optional sequence or mapping, parameters to use with query.

            Note: If args is a sequence, then %s must be used as the
            parameter placeholder in the query. If a mapping is used,
            %(key)s must be used as the placeholder.

            Returns long integer rows affected, if any

            """

    • callproc( procname, args):执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
    • executemany(sql, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
    • nextset():移动到下一个结果集

    3 接收返回值:也是使用cursor对象的方法进行接收

    • fetchone():返回一条结果
    • fetchall():返回全部结果
    • fetchmany(size=None):返回size条结果。如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据
    • scroll(value, mode='relative'):移动指针到某一行.
    • mode='relative',则表示从当前所在行移动value条
    • mode='absolute',则表示从结果集的第一 行移动value条.

    4 关闭数据库:需要关闭cursor对象connect对象

    1.3 举例

      1 #配置文件=============================
      2 #DB配置文件
      3 [db]
      4 host = 127.0.0.1
      5 port = 3306
      6 user = root
      7 passwd =
      8 dbname = test
      9 
     10 #配置文件解析类=============================
     11 #!/usr/bin/env python
     12 # coding=utf-8
     13 
     14 import ConfigParser
     15 
     16 class Configer(object):
     17     
     18     #构造函数,初始化ConfigParser类,并读取config文件
     19     def __init__(self , filePath):
     20         self.conf = ConfigParser.ConfigParser()
     21         self.conf.read(filePath)
     22     
     23     #获取key的value 
     24     def getConf(self , section , key):
     25         result = self.conf.get(section, key)
     26         return result
     27 
     28 #解析配置文件=============================
     29 #!/usr/bin/env python
     30 # coding=utf-8
     31 
     32 from testdb.Configer import *
     33 
     34 class db(object):
     35     conf = Configer("./db.conf")
     36     host = conf.getConf('db', 'host')
     37     port = conf.getConf('db', 'port')
     38     user = conf.getConf('db', 'user')
     39     passwd = conf.getConf('db', 'passwd')
     40     dbname = conf.getConf('db', 'dbname')
     41 
     42 #数据库封装及测试=============================
     43 #!/usr/bin/env python
     44 #encoding=UTF-8
     45 
     46 from MySQLdb import *
     47 import sys
     48 from testdb.db import *
     49 
     50 # print db.host
     51 class MySQLEngine(object):
     52      
     53     def __init__(self):
     54         self.conn = None
     55         self.cur = None
     56          
     57     '''
     58             打开数据库
     59     '''
     60     def open(self,dbHost,dbPort,dbUser,dbPasswd,dbName):
     61         self.conn = connect(host=dbHost,port=dbPort,user=dbUser,passwd=dbPasswd,db=dbName,charset='utf8')
     62         self.cur = self.conn.cursor()   #拿到游标,sql语句需要游标执行
     63     '''
     64         查询一条
     65     '''     
     66     def searchOne(self,sql):
     67         affRows = self.cur.execute(sql) #通过游标执行查询操作,返回影响行数
     68         res = self.cur.fetchone()   
     69         return res,affRows
     70     '''
     71         查询指定条数
     72     '''     
     73     def searchMany(self,sql,size):
     74         affRows = self.cur.execute(sql) #通过游标执行查询操作,返回影响行数
     75         res = self.cur.fetchmany(size)  #每条结果都是一个tuple,所有tuple最终组成一个tuple
     76         return res,affRows
     77     '''
     78         查询所有
     79     '''
     80     def searchAll(self,sql):
     81         affRows = self.cur.execute(sql) #通过游标执行查询操作,返回影响行数
     82         res = self.cur.fetchall()
     83         return res,affRows
     84     '''
     85         该改记录,包括:增、删、改
     86     '''
     87     def modify(self,sql,params):
     88         affRows = self.cur.execute(sql,params)
     89         self.conn.commit()  #不commit不会修改到数据库中
     90         return affRows
     91     '''
     92         关闭数据库
     93     '''
     94     def close(self):
     95         self.cur.close()
     96         self.conn.close()
     97          
     98 #实例化
     99 mysql = MySQLEngine()
    100 #连接数据库
    101 mysql.open(db.host,int(db.port),db.user,db.passwd,db.dbname)
    102 #单个查询
    103 (result,affRows) = mysql.searchOne('SELECT * FROM t_redis WHERE id=1;')
    104 print result[2]
    105 print affRows
    106 #指定个数查询
    107 (result,affRows) = mysql.searchMany('SELECT * FROM t_redis WHERE id>1;' , 3)
    108 print result
    109 print affRows
    110 #插入
    111 sql = "INSERT INTO t_redis(test_id , test_info) VALUES(%s,%s);"
    112 params = ('00019','豆腐')
    113 print mysql.modify(sql, params)
    114 mysql.close()
    115 
    116 #测试结果=============================
    117 张飞
    118 1
    119 
    120 ((2, u'2', u'info_2'), (5, u'0005', u'u7a7au7075'), (15, u'00015', u'u5c06u519b'))
    121 6
    122 
    123 1
    View Code

     2 xlutils Excel

    2.1 简介

    python处理excel文件主要是第三方模块库xlrd、xlwt、xluntils

    • xlrd读取excel但是不能对其进行操作
    • xlwt生成excel文件,不能在已有的excel文件基础上进行修改
    • 如需要修改文件就要使用xluntils模块

    2.2 安装

    • xlutils 依赖xlrd和xlwt,pip install xlutils 安装会自动安装xlrd和xlwt
    • xlutils 只能处理xls文件

     2.3 举例

     1 #!/usr/bin/env python
     2 # coding=utf-8
     3 
     4 from xlrd import open_workbook
     5 from xlutils.copy import copy
     6 #
     7 rbook = open_workbook(u'C:\测试数据2.xls')
     8 rsheet = rbook.sheet_by_name('测试用例')
     9 wbook = copy(rbook)
    10 #读操作
    11 print rsheet.cell(1,1).value
    12 #写操作,通过get_sheet()获取的sheet有write()方法
    13 wsheet = wbook.get_sheet(0)
    14 wsheet.write(2, 4, 'changed!')
    15  
    16 wbook.save(u'C:\测试数据2.xls')
    View Code

     3 openpyxl Excel

    3.1 简介

    A Python library to read/write Excel 2007 xlsx/xlsm files

    openpyxl是Python处理表格的库之一,但是它是处理excel2007/2010的格式,也就是xlsx系列,如果要处理以前的2003的表格(xls),那么则要用另外的库

    如果只是要进行表格数据读取和进行简单的写数据的话,推荐使用openpyxl

    3.2 安装

    openpyxl依赖jdcal ,pip install openpyxl安装会自动安装jdcal 

    3.3 举例

     1 #!/usr/bin/env python
     2 # coding=utf-8
     3 from openpyxl.workbook import Workbook
     4 from openpyxl.reader.excel import load_workbook
     5 
     6 #指定excel
     7 book = load_workbook(filename=u'C:\测试数据3.xlsx')  
     8 #指定sheet页
     9 sheet = book.get_sheet_by_name('xml字段')
    10 #最大行列数
    11 print sheet.max_row
    12 print sheet.max_column
    13 # column=len(sheet.column)
    14 #获取指定cell的值
    15 print sheet.cell(row=2, column=1).value
    16 #指定cell写入值
    17 sheet.cell(row=6,column=6).value = "value3333"
    18 #保存
    19 book.save(u'C:\测试数据3.xlsx')
    View Code
  • 相关阅读:
    计算成像最新进展及应用
    计算成像资料笔记
    成像中的倏逝波与衍射极限
    Eclipse安装Activiti插件(流程设计器)
    Python3.x:代理ip刷评分
    Python3.x:代理ip刷点赞
    Python3.x:正则 re.findall()的用法
    Python3.x:python: extend (扩展) 与 append (追加) 的区别
    Python3.x:zip()函数
    Python3.x:获取代理ip以及使用
  • 原文地址:https://www.cnblogs.com/lizitest/p/6664037.html
Copyright © 2020-2023  润新知