main.cpp
#include "display_da.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
// QApplication::addLibraryPath("./plugins");
QApplication a(argc, argv);
display_da w;
w.show();
return a.exec();
}
sql_interface.h
#ifndef SQL_INTERFACE_H
#define SQL_INTERFACE_H
#include <QString>
#include <QtCore>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQueryModel>
#include <QtGui/QMessageBox>
#include <qtableview.h>
#include <QtGui/QComboBox>
#include <qsqlerror.h>
class SqlClass : public QObject
{
Q_OBJECT
private:
QSqlDatabase* db;
QString db_driver,host_name,db_name,user_name,pass_word;
public:
SqlClass(QObject* parent = 0,
QString Driver = "QODBC",QString HostName = "172.18.19.16",QString DbName = "db_wuliu",QString UserName = "sa",QString PassWd = "903198975");
virtual ~SqlClass();
public:
void query_sql(QComboBox *);
};
#endif //SQL_INTERFACE_H
sql_interface.cpp
#include "sql_interface.h"
SqlClass::SqlClass(QObject* parent /* = 0 */, QString Driver /* = "QMYSQL" */,QString HostName /* = "localhost" */,QString DbName /* = "weixin_db" */,QString UserName /* = "root" */,QString PassWd /* = "123123" */) : QObject(parent),db_driver(Driver),host_name(HostName),db_name(DbName),user_name(UserName),pass_word(PassWd)
{
db = &QSqlDatabase::addDatabase(db_driver);
if( !db->isValid() ){
qDebug()<< db->lastError().text();
}
db->setHostName(host_name);
db->setDatabaseName("DRIVER={SQL SERVER};SERVER="+host_name+";DATABASE="+db_name);
db->setUserName(user_name);
db->setPassword(pass_word);
if( !db->open() ){
QMessageBox::warning(NULL,"database error","Cannot open DB",QMessageBox::Cancel);
}
else{
QMessageBox::information(NULL,"connected database","please chose the game version",QMessageBox::Ok);
}
}
void SqlClass::query_sql(QComboBox *need_add)
{
QSqlQueryModel* result_model = new QSqlQueryModel();
const QSqlDatabase& database= *db;
result_model->setQuery("SELECT * from dbo.t_user",database);
qDebug()<<database.lastError().text();
need_add->setModel(result_model);
}
SqlClass::~SqlClass()
{
}
display_da.h
#ifndef DISPLAY_DA_H
#define DISPLAY_DA_H
#include <QtGui/QMainWindow>
#include "ui_display_da.h"
#include "sql_interface.h"
class display_da : public QMainWindow
{
Q_OBJECT
private:
Ui::display_daClass ui;
SqlClass* mainSql;
public:
display_da(QWidget *parent = 0, Qt::WFlags flags = 0);
~display_da();
};
#endif // DISPLAY_DA_H
display_da.cpp
#include "display_da.h"
display_da::display_da(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
mainSql = new SqlClass(this);
mainSql->query_sql(ui.select_gv_combo);
}
display_da::~display_da()
{
}
效果: