Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection to SQL Server with qt [closed]

Tags:

sql

qt

How can I connect to SQL Server with Qt ?

like image 485
ayla Avatar asked Jun 17 '10 10:06

ayla


People also ask

How do I add a connection to PopSQL?

Connecting to your databaseVisit the PopSQL web app at app.popsql.com. In the top center of the page, click Manage Connections. Create a new connection and enter your database host, username, password, and any other relevant credentials.

Can T Remote connect to SQL Server?

Right-click on your server name and click 'Properties'. Go to the Security page for Server Authentication, and select 'SQL Server and Windows Authentication' mode. Then, go to the Connections page and ensure that "Allow remote connections to this server" is checked, and click OK.

How do I connect to Mssqlserver instance?

Connect to a SQL Server instanceStart SQL Server Management Studio. The first time you run SSMS, the Connect to Server window opens. If it doesn't open, you can open it manually by selecting Object Explorer > Connect > Database Engine. For Server type, select Database Engine (usually the default option).


2 Answers

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

like image 102
Harald Scheirich Avatar answered Oct 29 '22 04:10

Harald Scheirich


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();
}
like image 5
Nemo Avatar answered Oct 29 '22 03:10

Nemo