How to use ODBC in Qt

ODBC (Open Database Connectivity) drivers allow connection to many databases out of the box. In Windows and Qt you can use ODBC Plugin (for Qt) to connect to those databases.

You can access details of all existing drivers from control panel or by simply searching for ODBC keyword using windows search:

ODBC
ODBC


To use ODBC drivers in Qt start with adding sql to your project’s (qmake .PRO file) required modules.

QT += sql

Then include QtSql in your headers files:

#include <QtSql>

Now define a QSqlDatabse in your MainWindow (or any other window that you want to use ODBC)

QSqlDatabase db;

Now to be able to perform standard SQL queries on QSqlDatabase, you have to open it the correct way. In this example I have demonstrated connecting to Visual FoxPro drivers but the process should be quite similar for any other driver, as long as you know what the parameters mean:

db.setDatabaseName
(
	"Driver={Microsoft Visual FoxPro Driver};"
	"SourceType=DBF;"
	"SourceDB=C:\MyDataFiles\;"
	"Exclusive=No;"
	"Collate=Machine;"
	"NULL=No;"
	"DELETED=No;"
	"BACKGROUNDFETCH=No;"
);
db.open();

Consequently you can use QSqlQuery (refer to Qt documentation) to perform any SQL query that you need. Good luck!



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.