PDA

View Full Version : connect mysql with odbc



qtcoba
18th April 2011, 04:06
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QtSql"
#include "QLabel"
#include "QMessageBox"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::on_pushButton_clicked()
{
QSqlDatabase n=new QSqlDatabase();
n->addDatabase("QODBC3","ahm");
n->setHostName("10.0.0.101");
n->setDatabaseName("Driver={MySQL ODBC 5.1.8 Driver};DATABASE=ahm;");
n->setUserName("ahm");
n->setPassword("ahmdtcahm");
n->setPort(3306);

/*if (!n->open()) {

QMessageBox::critical(0, QObject::tr("Database Error"),

n->lastError().text());
}*/
bool cek=n->open();
if(cek==true)
{
QLabel *l=new QLabel();
l->setText("connect");
l->show();
}
else
{
QLabel *l=new QLabel();
l->setText("can't connect");
l->show();

}
}

and output is can't connect...how can i solve this problem???

mcosta
18th April 2011, 10:51
Are ODBC correctly configured? What is the Error Message?

ChrisW67
18th April 2011, 23:12
As written your code won't even compile. At line 22: you try to treat a pointer to an object as an actual object. At line 23: QSqlDatabase::addDatabase() is a static method and you need to use it correctly (as in the examples in the documentation or this site). Try the SQL Widget Mapper Example.