PyMySQL简单调用

PyMySQL应用简单说明:

参考文档:https://pypi.org/project/PyMySQL/

  • 安装:pip install PyMySQL
  • 检测:pip list
  • Demo -- MySQL数据库 "连接""插入""查询"
# -*- coding:utf-8 -*-

import pymysql.cursors

# insert method
def insert_db_test(connection, sql, records):
    try:
        with connection.cursor() as cursor:
            # loop
            for record in records:
                # Create a new record
                cursor.execute(sql, record)
    except Exception as e:
        print('---- error:', e)
    finally:
        # connection is not autocommit by default. So you must commit to save your changes.
        connection.commit()
        print('---- Insert Record Over !!!')


# select method
def select_db_test(connection, sql, condition):
    result = None
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql, condition)
            # result = cursor.fetchall()
            result = cursor.fetchone()
    except Exception as e:
        print('---- error:', e)
    finally:
        print('---- Select Record Over !!!')

    return result


if __name__ == '__main__':
    # Connect to the database
    db_connection = pymysql.connect(host='localhost',
                                 user='****',
                                 password='******',
                                 db='testdb',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    # insert records
    print('---- Insert Record ...')
    # insert_sql = "INSERT INTO `student` (`id`, `name`, `sex`, `birth`, `department`, `address`) VALUES (%s, %s, %s, %s, %s, %s)"
    insert_sql = "INSERT INTO student (id, name, sex, birth, department, address) VALUES (%s, %s, %s, %s, %s, %s)"
    insert_record_list = [(1003, '刘五', '女', 1977, '数学系', '山东省青岛市'),
                (1004, '刘六', '男', 1976, '音乐系', '山东省济南市'),
                (1005, '刘七', '女', 1975, '美术系', '山东省烟台市'),
                (1006, '刘八', '男', 1974, '电子系', '山东省潍坊市')]
    insert_db_test(db_connection, insert_sql, insert_record_list)

    # select record
    print('---- Select Record ...')
    select_sql = "SELECT * FROM student WHERE id=%s"
    select_condition = (1004,)
    result = select_db_test(db_connection, select_sql, select_condition)
    print('---- Result:', result)

    # Close db connnection
    db_connection.close()



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Awesome Python [![Awesome](https://cdn.rawgit.com/sindr...
    emily_007阅读 2,227评论 0 3
  • 内容来源于《Web接口开发与自动化测试——基于Python语言》虫师编著,如有涉及版权问题,归虫师本人所有。请大家...
    无罪的坏人阅读 1,946评论 1 3
  • 模块(包)管理工具pip优点 版本控制 依赖处理 pip文档:https://pip.pypa.io/en/lat...
    fuadon阅读 3,123评论 0 1
  • 两年前第一次接触termux,当时很兴奋,下班没事就折腾一番,试着装各种软件,记忆比较深刻的是在上面装了一套fed...
    费斯布莱克阅读 8,102评论 2 24
  • 第二天朱歆斟酌好久,终于发出了干巴巴的五个字,“我要结婚了!”她心神不宁,时不时点点微信,没有来自沈逸程的红点。后...
    琥琥妞阅读 400评论 0 1