#include "SqlExecute.h"
#include <QSqlRecord>
#include <QSqlField>
#include "SqlCore.h"
#include <QDebug>
 
SqlExecute::SqlExecute(QObject * parent/*=NULL*/)
{

}

SqlExecute::~SqlExecute()
{

}
 
void SqlExecute::init(QString sDriver, QString sUser, QString sPasswd, QString sDBFile)
{
    SqlCore::init(sDriver, sUser, sPasswd, sDBFile);
    SqlCore::getSqlDataBase();
}

bool SqlExecute::exeRead(QString sql, QList<QVariantMap> &list)
{
	bool ok;
    QSharedPointer<QSqlQuery> m_sqlQuery = SqlCore::select(sql, ok);
	if (!ok)
	{
        //logInfo()<< QString::fromLocal8Bit("error:[%1]£¬Ö´ÐÐ[%2]").arg(m_sqlQuery->lastError().text()).arg(sql) << endl;
		m_sqlQuery->finish();
		m_sqlQuery->clear();
		return false;
	}
	while (m_sqlQuery->next()) 
	{
		QVariantMap map;
		for (int i = 0; i < m_sqlQuery->record().count(); i++)
		{
			    map.insert(m_sqlQuery->record().field(i).name(),
				m_sqlQuery->record().field(i).value());
		}
		list.append(map);
	} ;
	m_sqlQuery->finish();
	m_sqlQuery->clear();
	return true;
}

 
bool SqlExecute::exeRead(QString sql, QList<QList<QVariant>> &list, QStringList sResuleSeq)
{
	bool ok;
    QSharedPointer<QSqlQuery> m_sqlQuery = SqlCore::select(sql, ok);
	if (!ok)
	{
        //logInfo() << QString::fromLocal8Bit("error:[%1]£¬Ö´ÐÐ[%2]").arg(m_sqlQuery->lastError().text()).arg(sql) << endl;
		m_sqlQuery->finish();
		m_sqlQuery->clear();
		return false;
	}

	while (m_sqlQuery->next())
	{
		QList<QVariant> listdata;
		for (int i = 0; i < m_sqlQuery->record().count(); i++)
		{
			int nameCol =  m_sqlQuery->record().indexOf(sResuleSeq.at(i));
			listdata.append(m_sqlQuery->value(nameCol));
		}
		list.append(listdata);
	};
	m_sqlQuery->finish();
	m_sqlQuery->clear();
	return true;
}

bool SqlExecute::exeWrite(QString sql)
{
	bool ok;
    QSharedPointer<QSqlQuery> m_sqlQuery = SqlCore::select(sql, ok);
	if (!ok)
	{
        //logInfo() << QString::fromLocal8Bit("error:[%1]£¬Ö´ÐÐ[%2]").arg(m_sqlQuery->lastError().text()).arg(sql) << endl;
		m_sqlQuery->finish();
		m_sqlQuery->clear();
		return false;
	}
	m_sqlQuery->finish();
	m_sqlQuery->clear();
	return true;
}

void SqlExecute::destroyConn()
{
    SqlCore::destroyConn();
}

QSqlDatabase SqlExecute::getDataBase()
{
	 
    return 	SqlCore::getSqlDataBase();
 
}

QList<QVariantMap> SqlExecute::getValues(QSharedPointer<QSqlQuery> sqlQuery, int page, int pageNum)
{
	QList<QVariantMap> list;
	if (!sqlQuery->seek(page))
	{
		return list;
	}
	do
	{
		QVariantMap map;
		for (int i = 0; i < sqlQuery->record().count(); i++)
		{
			map.insert(sqlQuery->record().field(i).name(),
				sqlQuery->record().field(i).value());
		}
		list.append(map);
	} while (sqlQuery->next() && --pageNum);
	return list;
}

