Connect To sqlServer Database Problem
-
Hello,
i Want To Connect To a database from SQL SERVER and I Wrote This Codes But
Dose Not Worked!anybody can Help me Please?
Codes:#include "mainwindow.h" #include "ui_mainwindow.h" #include <QSql> #include <QSqlDatabase> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QString serverNam="localhost\\QSQLSERVER"; QString dbname="msdb"; QSqlDatabase db=QSqlDatabase::addDatabase("QODBC"); db.setConnectOptions(); QString dsn=QString("DRIVER={SQL Server};Server=%1;DATABASE=%2,Trusted_Connection=Yes;").arg(serverNam).arg(dbname); db.setDatabaseName(dsn); if(!db.open()) { QMessageBox *sts=new QMessageBox; sts->setText("faild!"); sts->exec(); } } MainWindow::~MainWindow() { delete ui; }
Sql Server Screenshot
Note:
I addedQT += sql
code in my .Pro File
Thanks.
-
Hi,
Might be a silly question but, are you sure you have the driver QODBC availalbe.
-
@SGaist
what you error caught during execution? -
@Vicky-Sharma
Just Show my Message in IF CONDITION that show "fail"!
and my ODBC Drivers Already Installed. -
Rather than fail you should print the content of QSqlDatabase::lastError.
-
@SGaist
@Vicky-Sharma
Thanks
this is my Error
http://8pic.ir/images/kab0zjxk7ytw9yao2rxe.png
What i must do Exactly ? -
As silly as it may sound, fix the problem described by the message. Either your server is not accessible e.g. doesn't run or you can't access it because of missing credentials.
-
@hskoglund
Thanks
i Replaced that ip But Showed Me This Message
ERROR
Sql Server -
Aha, ok, then instead try specify your name and password:
QString dsn="DRIVER=SQL Server;Server=LocalHost;Database=Test;uid=Doctor Corpartion;pwd=MyPassword";
note: also I changed from 127.0.0.1 to LocalHost (it's the same)
EDIT: forgot to say: also try with username/password for your SQL Server, usually the username is sa