#!/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()
posted on 2018-12-05 11:27  新美好时代  阅读(533)  评论(0编辑  收藏  举报