How can I connect to SQL Server with Qt ?
-
QT seem to have an ODBC driver which you can use to connect to mssql. Here's the relevant docs: doc.qt.nokia.com/4.6/… – shoosh Jun 17 '10 at 10:47
-
1Why is this not a question? There are only a few ways to connect to SQL Server from Qt and this question cannot be categorized as "difficult to tell what is being asked here". – Nemo Feb 11 '15 at 21:10
Qt supports ODBC, to connect to an odbc database using a QSqlDatabase
you 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 that error.
If you built Qt from scratch you might have to enable the building of the odbc plugin
-
@HeraldScheirich, what does
connectionName
hold? Database name? Thanks! – Rachael Mar 3 '15 at 17:14 -
connectionName
is just an identifier when you calladdDatabase()
you can have multiple connections/databases open,QSqlDatabase::database(connectionName)
can be used to retrieve the db with the given identifier – Harald Scheirich Mar 4 '15 at 13:33 -
Hi, you if always the string connectio have the structure: "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;", or sometimes can change? – APRocha May 18 '15 at 22:24
On Windows, you could also connect to a database using a DSN. In this example, a DSN named "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();
}