zoukankan      html  css  js  c++  java
  • pymysql操作mysql

    一、使用PyMySQL操作mysql数据库

    适用环境

    python版本 >=2.6或3.3
    mysql版本>=4.1

    安装

    可以使用pip安装也可以手动下载安装。使用pip安装,在命令行执行如下命令:

    pip install PyMySQL
    

    手动安装,请先下载。下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。其中的X.X是版本。

    下载后解压压缩包。在命令行中进入解压后的目录,执行如下的指令:

    python setup.py install
    

    建议使用pip安装

    二、使用示例

    连接数据库如下:

    import pymysql.cursors
    
    # Connect to the database
    connection = pymysql.connect(host='127.0.0.1',
        port=3306,
        user='root',
        password='zhyea.com',
        db='employees',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    也可以使用字典进行连接参数的管理,我觉得这样子更优雅一些

    import pymysql.cursors
    
    config = {
        'host':'127.0.0.1',
        'port':3306,
        'user':'root',
        'db':'employees',
        'charset':'utf8mb4',
        'cursorclass':pymysql.cursors.DictCursor,
    }
    
    # Connect to the database
    connection = pymysql.connect(**config)

    插入数据:

    执行sql语句前需要获取cursor,因为配置默认自动提交,故在执行sql语句后需要主动commit,最后不要忘记关闭连接:

    from datetime import date, datetime, timedelta
    import pymysql.cursors
     
    # 连接配置信息
    config = {
              'host':'127.0.0.1',
              'port':3306,
              'user':'root',
              'password':'zhyea.com',
              'db':'employees',
              'charset':'utf8mb4',
              'cursorclass':pymysql.cursors.DictCursor,
              }
    # 创建连接
    connection = pymysql.connect(**config)
     
    # 获取明天的时间
    tomorrow = datetime.now().date() + timedelta(days=1)
     
    # 执行sql语句
    try:
        with connection.cursor() as cursor:
            # 执行sql语句,插入记录
            sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'
            cursor.execute(sql, ('Robin''Zhyea', tomorrow, 'M', date(1989, 6, 14)));
        # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
        connection.commit()
     
    finally:
        connection.close();

    执行查询

    import datetime
    import pymysql.cursors
     
    #连接配置信息
    config = {
              'host':'127.0.0.1',
              'port':3306,
              'user':'root',
              'password':'zhyea.com',
              'db':'employees',
              'charset':'utf8mb4',
              'cursorclass':pymysql.cursors.DictCursor,
              }
    # 创建连接
    connection = pymysql.connect(**config)
     
    # 获取雇佣日期
    hire_start = datetime.date(1999, 1, 1)
    hire_end = datetime.date(2016, 12, 31)
     
    # 执行sql语句
    try:
        with connection.cursor() as cursor:
            # 执行sql语句,进行查询
            sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'
            cursor.execute(sql, (hire_start, hire_end))
            # 获取查询结果
            result = cursor.fetchone()
            print(result)
        # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
        connection.commit()
     
    finally:
        connection.close();

    这里的查询支取了一条查询结果,查询结果以字典的形式返回

    从结果集中获取指定数目的记录,可以使用fetchmany方法:

    result = cursor.fetchmany(2)

    不过不建议这样使用,最好在sql语句中设置查询的记录总数。

    获取全部结果集可以使用fetchall方法:

    result = cursor.fetchall()

    因为只有两条记录,所以上面提到的这两种查询方式查到的结果是一样的:

    [
     {'last_name''Vanderkelen''hire_date': datetime.date(2015, 8, 12), 'first_name''Geert'},
     {'last_name':'Zhyea''hire_date': datetime.date(2015, 8, 21), 'first_name''Robin'}
    ]

    三、在django中使用

    设置DATABASES和官方推荐使用的MySQLdb的设置没什么区别:

    DATABASES = {
       'default': {
            'ENGINE''django.db.backends.mysql',
            'NAME''mytest',
            'USER''root',
            'PASSWORD''zhyea.com',
            'HOST''127.0.0.1',
            'PORT''3306',
        }
    }

    关键是这里:我们还需要在站点的__init__.py文件中添加如下的内容:

    import pymysql
    pymysql.install_as_MySQLdb()



  • 相关阅读:
    ECshop 二次开发模板教程4
    ECshop 二次开发模板教程3
    ECshop 二次开发模板教程2
    ECshop 二次开发模板教程1
    ecshop 二次开发及模板标签
    ECSHOP seo修改建议
    Ecshop ajax 局部刷新购物车功能
    ECSHOP
    echo二次开发 ecshop 函数列表
    Ecshop文件结构,二次开发
  • 原文地址:https://www.cnblogs.com/0zcl/p/9163620.html
Copyright © 2011-2022 走看看