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()
  • 相关阅读:
    课堂作业04 2017.10.27
    课程作业 03 动手动脑 2017.10.20
    课程作业 03 2017.10.20
    HDU 3974 Assign the task
    POJ 2155 Matrix
    POJ 2481 Cows
    HDU 3038 How Many Answers Are Wrong
    CS Academy Array Removal
    POJ_1330 Nearest Common Ancestors LCA
    CF Round 427 D. Palindromic characteristics
  • 原文地址:https://www.cnblogs.com/NiceTime/p/10069930.html
Copyright © 2011-2022 走看看