zoukankan      html  css  js  c++  java
  • python3操作mysql数据库表01(封装查询单条、多条数据)

    #!/usr/bin/env python
    # -*- coding:UTF-8 -*-

    import pymysql
    # import os
    '''
    封装查询单条、多条数据
    '''
    # os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    pdbinfo = {"host": '912.168.1.133',
    "port": 3306,
    "user": 'root',
    "passwd": '123456',
    "db": 'employees',
    "charset": 'utf8'}


    class MySQLUtil:
    def __init__(self):
    self.dbinfo=pdbinfo
    self.conn=MySQLUtil.__getConnect(self.dbinfo)


    @staticmethod
    def __getConnect(pdbinfo):
    try:
    conn=pymysql.connect(host=pdbinfo['host'],port=pdbinfo['port'],user=pdbinfo['user'],passwd=pdbinfo['passwd'],
    db=pdbinfo['db'],charset=pdbinfo['charset'])
    return conn
    except Exception as error:
    print("get connect happen error %s "%error)

    def close_db(self):
    try:
    self.conn.close()
    except Exception as error:
    print("close db happen error %s "%error)

    def get_alldata(self,psql):
    cur=self.conn.cursor()
    try:
    cur.execute(psql)
    except Exception as error:
    print("execute sql happen error %s "%error)
    else:
    rows = cur.fetchall()
    cur.close()
    return rows

    def get_singledata(self,psql):
    rows = self.get_alldata(psql)
    row_len=len(rows)
    # print(row_len)

    # if rows != None:
    # for row in rows:
    # for i in row:
    # print(i)
    # return i


    if __name__=='__main__':
    conn=MySQLUtil()

    selectSql = "select * from salaries sal where sal.salary > '%d'" % (150000)

    rows=conn.get_alldata(selectSql)

    # for i,element in enumerate(rows):
    # print(i,element)
    # print(rows)

    # row=conn.get_singledata(selectSql)
    # print(row)

    for i in rows:
    listRes=list(i)
    print(listRes[2])

    conn.close_db()
  • 相关阅读:
    设计模式--22、状态模式
    设计模式--21、备忘录模式
    设计模式--20、迭代器模式
    关于分布式事务、两阶段提交协议、三阶提交协议
    分布式系统的一致性探讨
    分布式系统的BASE理论
    分布式系统的CAP理论
    Kafka集群环境搭建
    Elasticsearch插件head的安装(有坑)
    centos6 x64安装elasticsearch5.5.2启动报错
  • 原文地址:https://www.cnblogs.com/NiceTime/p/10069930.html
Copyright © 2011-2022 走看看