#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""DB共享类库"""
# 使用此类,先实例化一个DataBaseParent_local对象,然后对象调用相应方法
# from django.db import connection
import MySQLdb
db = MySQLdb.connect(host="www.szoworld.cn", user="db_test", passwd="qazedc", db="pram_sg", charset="utf8")
class DataBaseParent_local:
def __init__(self):
self.cursor = "Initial Status"
self.cursor = db.cursor()
if self.cursor == "Initial Status":
raise Exception("Can't connect to Database server!")
# 返回元组套元组数据
def select(self, sqlstr):
# result = (('apollo', 'male', '164.jpeg'), ('apollo', 'male', ''))
cur = db.cursor()
cur.execute(sqlstr)
List = cur.fetchall()
iTotal_length = len(List)
self.description = cur.description
cur.close()
return List, iTotal_length
# 返回列表套字典数据
def select_include_name(self, sqlstr):
# result = [{'name':'apollo','age':28},{'name':'jack','age':27}]
cur = db.cursor()
cur.execute(sqlstr)
index = cur.description
List = cur.fetchall()
iTotal_length = len(List)
result = []
for res in List:
row = {}
for i in range(len(index) - 1):
row[index[i][0]] = res[i]
result.append(row)
cur.close()
return result, iTotal_length
# 返回指定页码数据(元组套元组)
def select_for_grid(self, sqlstr, pageNo=1, select_size=5):
# List: (('apollo','male','28'),('jack','male','27'))
# iTotal_length: 查询结果元组的长度
# select_size:分页每页显示
# pageNo:页码
List, iTotal_length = self.select(sqlstr)
# 确定页码
if iTotal_length % select_size == 0:
iTotal_Page = iTotal_length / select_size
else:
iTotal_Page = iTotal_length / select_size + 1
start, end = (pageNo - 1) * select_size, pageNo * select_size
if end >= iTotal_length: end = iTotal_length
if iTotal_length == 0 or start > iTotal_length or start < 0:
return [], iTotal_length, iTotal_Page, pageNo, select_size
# 假设有10条数据,select_size=5,对应结果如下:
# List[start:end]:(('apollo','male','28'),('jack','male','27')) 10,2,
# iTotal_length:10
# iTotal_Page:2
# pageNo:1
# select_size:5
return List[start:end], iTotal_length, iTotal_Page, pageNo, select_size
# 执行sql语句
def executesql(self, sqlstr):
cur = db.cursor()
r = cur.execute(sqlstr)
db.commit()
cur.close()
return r
# 插入数据
def insert(self, sql, param):
cur = self.cursor
n = cur.execute(sql, param)
db.commit()
cur.close()
return n
def release(self):
return 0