Connect to SQL Server with qt

How can I connect to SQL Server with Qt?

+5
source share
2 answers

Qt supports ODBC, to connect to the odbc database using, QSqlDatabaseyou can use the following code

QString connectionTemplate = "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;";

QString connectionString = connectionTemplate.arg(server).arg(dbName);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", connectionName);

db.setDatabaseName(connectionString);
db.setUserName(user);
db.setPassword(password);

if (db.open())
{

}
else
{

}

Most or all of the QSql classes ... return an error, it is a very good habit to always check for this error.

If you built Qt from scratch, you might have to enable odbc plugin building

+7
source

On Windows, you can also connect to the database using a DSN. In this example, a DSN called Orders is created and used.

//Load Odbc driver
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");

//Set DSN
db.setDatabaseName("Orders");

//Connect to db
if(db.open())
{
    //Query
    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery("SELECT * FROM Orders ORDER BY Date DESC", db);

    //Display
    QTableView *view = new QTableView;
    view->setModel(model);
    view->show();
}
+5
source

All Articles