首页 > 代码库 > 3 Selenium Python 数据库及文件

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对象

 

3 Selenium Python 数据库及文件