Qt подключение к oracle
I have qt open source 5.12 and ubuntu 18.04. How do I connect to oracle 12c via ODBC? I tried:
1 Answer 1
Revised Answer:
Steps to configure and test ODBC connectivity to an Oracle 12.2 database in Qt Open Source 5.12 on Ubuntu 18.04:
1) Install pre-requisites (if they aren't already installed).
2) Install ODBC Driver Manager (unixODBC).
3) Install Oracle ODBC driver.
4) Create tnsnames.ora file and add your database connection to it.
5) Run odbc_update_ini.sh , which creates/updates the unixODBC configuration needed to register the Oracle ODBC driver with unixODBC and partially configure an Oracle ODBC data source.
Expected contents of unixODBC config files after running odbc_update_ini.sh:
6) "Chown" ~/.odbc.ini to the uid/gid of the currently-logged in user. This file is initially created as root:root. If the ownership is not changed, database connections through the ODBC driver may fail.
7) Complete the data source configuration by adding/updating the ~/odbc.ini parameters shown below.
9) Update .bash_profile with Oracle environment variables and source the file.
10) Verify connection to Oracle ODBC data source.
11) Create program to test ODBC connectivity to Oracle.
Expected output (table names may vary):
Above steps were verified on OS / Qt version below:
Original Answer:
It looks like you're trying to use an ODBC driver for SQL Server to connect to Oracle, which doesn't make sense to me.
Note: You should use the native driver, if it is available, instead of the ODBC driver. ODBC support can be used as a fallback for compliant databases if no native driver is available.
The information about building with the native Oracle OCI driver is here
You can download the Oracle instant client that contains the OCI driver from here. According to the QT docs, you'll need Instant Client Package - Basic" and "Instant Client Package - SDK". If you still want to use ODBC, then you could try downloading Oracle's "ODBC Package - Additional libraries for enabling ODBC applications" on the instant client download page. For all of these downloads, make sure that you get the client version corresponding to your database.
Qt дает возможность создания платформо-независимых приложений для работы с базами данных, используя стандартные СУБД. Qt включает «родные» драйвера для Oracle, Microsoft SQL Server, Sybase Adaptive Server, IBM DB2, PostgreSQL, MySQL и ODBC-совместимых баз данных. Qt включает специфичные для баз данных виджеты, а также поддерживает расширение для работы с базами данных любых встроенных или отдельно написанных виджетов.
Введение
Работа с базами данных в Qt происходит на различных уровнях:
1.Слой драйверов — Включает классы QSqlDriver, QSqlDriverCreator, QSqlDriverCreatorBase, QSqlDriverPlugin и QSqlResult. Этот слой предоставляет низкоуровневый мост между определенными базами данных и слоем SQL API.
2.Слой SQL API — Этот слой предоставляет доступ к базам данных. Соединения устанавливаются с помощью класса QSqlDatabase. Взаимодействие с базой данных осуществляется с помощью класса QSqlQuery. В дополнение к классам QSqlDatabase и QSqlQuery слой SQL API опирается на классы QSqlError, QSqlField, QSqlIndex и QsqlRecord.
3.Слой пользовательского интерфейса — Этот слой связывает данные из базы данных с дата-ориентироваными виджетами. Сюда входят такие классы, как QSqlQueryModel, QSqlTableModel и QSqlRelationalTableModel.
Соединение с базой данных
- QDB2 — IBM DB2 (версия 7.1 и выше
- QIBASE — Borland InterBase
- QMYSQL — MySQL
- QOCI — Драйвер Oracle Call Interface
- QODBC — Open Database Connectivity (ODBC) — Microsoft SQL Server и другие ODBC-совместимые базы данных
- QPSQL — PostgreSQL (версия 7.3 и выше)
- QSQLITE2 — SQLite версии 2
- QSQLITE — SQLite версии 3
- QTDS — Драйвер Sybase Adaptive Server
Соединиться с базой данных можно вот так:
- QSqlDatabase db = QsqlDatabase::addDatabase( "QMYSQL" , "mydb" );
- db.setHostName( "bigblue" );
- db.setDatabaseName( "flightdb" );
- db.setUserName( "acarlson" );
- db.setPassword( "1uTbSbAs" );
- bool ok = db.open();
Первая строка создает объект соединения, а последняя открывает его. В промежутке инициализируется некоторая информация о соединении, включая имя соединения, имя базы данных, имя узла, имя пользователя, пароль. В этом примере происходит соединение с базой данных MySQL flightdb на узле bigblue. Аргумент «QMYSQL» в addDatabase() указывает тип драйвера базы данных, чтобы использовать для соединения, а «mydb» — имя соединения.
Как только соединение установлено, можно вызвать статическую функцию QSqlDatabase::database() из любого места программы с указанием имени соединения, чтобы получить указатель на это соединение. Если не передать имя соединения, она вернет соединение по умолчанию.
Если open() потерпит неудачу, он вернет false. В этом случае, можно получить информацию об ошибке, вызвав QSqlDatabase::lastError().
Для удаления соединения с базой данных, надо сначала закрыть базу данных с помощью QSqlDatabase::close(), а затем, удалить соединение с помощью статического метода QSqlDatabase::removeDatabase().
Выполнение инструкций SQL
Класс QSqlQuery обеспечивает интерфейс для выполнения SQL запросов и навигации по результирующей выборке.
Для выполнения SQL запросов, просто создают объект QSqlQuery и вызывают QSqlQuery::exec(). Например, вот так:
- QSqlQuery query;
- query.exec( "SELECT name, salary FROM employee WHERE salary > 50000" );
Конструктор QSqlQuery принимает необязательный аргумент QSqlDatabase, который уточняет, какое соединение с базой данных используется. Если его не указать, то используется соединение по умолчанию.
Если возникает ошибка, exec() возвращает false. Доступ к ошибке можно получить с помощью QSqlQuery::lastError().
QSqlQuery предоставляет единовременный доступ к результирующей выборке одного запроса. После вызова exec(), внутренний указатель QSqlQuery указывает на позицию перед первой записью. Если вызвать метод QSqlQuery::next() один раз, то он переместит указатель к первой записи. После этого необходимо повторять вызов next(), чтобы получать доступ к другим записям, до тех пор пока он не вернет false. Вот типичный цикл, перебирающий все записи по порядку:
QSqlQuery может выполнять не только SELECT, но также и любые другие запросы. Следующий пример вставляет запись в таблицу, используя INSERT:
- QSqlQuery query;
- query.exec( "INSERT INTO employee (id, name, salary) "
- "VALUES (1001, 'Thad Beaumont', 65000)" );
Если надо одновременно вставить множество записей, то зачастую эффективней отделить запрос от реально вставляемых значений. Это можно сделать с помощью вставки значений через параметры. Qt поддерживает два синтаксиса вставки значений: поименованые параметры и позиционные параметры. В следующем примере показана вставка с помощью поименованного параметра:
- QSqlQuery query;
- query.prepare( "INSERT INTO employee (id, name, salary) "
- "VALUES (:id, :name, :salary)" );
- query.bindValue( ":id" , 1001);
- query.bindValue( ":name" , "Thad Beaumont" );
- query.bindValue( ":salary" , 65000);
- query.exec();
- QSqlQuery query;
- query.prepare( "INSERT INTO employee (id, name, salary) "
- "VALUES (?, ?, ?)" );
- query.addBindValue(1001);
- query.addBindValue( "Thad Beaumont" );
- query.addBindValue(65000);
- query.exec();
При вставке множества записей требуется вызвать QSqlQuery::prepare() только однажды. Далее можно вызвать bindValue() или addBindValue() с последующим вызовом exec() столько раз, сколько потребуется.
Отображение данных в таблице-представлении
Классы QSqlQueryModel, QSqlTableModel и QSqlRelationalTableModel могут использоваться в качестве источников данных для классов представлений Qt, таких как QListView, QTableView и QTreeView. На практике наиболее часто используется QTableView в связи с тем, что результирующая SQL выборка, по существу, представляет собой двумерную структуру данных.
В следующем примере создается представление основанное на модели данных SQL:
- QSqlTableModel model;
- model.setTable( "employee" );
- QTableView *view = new QTableView;
- view->setModel(&model);
- view->show();
Если модель является моделью для чтения-записи (например, QSqlTableModel), то представление позволяет редактировать поля. Это можно отключить с помощью следующего кода
- view->setEditTriggers(QAbstractItemView::NoEditTriggers);
Можно использовать одну и ту-же модель в качестве источника данных для нескольких представлений. Если пользователь изменяет данные модели с помощью одного из представлений, другие представления немедленно отобразят изменения.
Классы-представления для обозначения колонок наверху отображают заголовки. Для изменения текста заголовка, используется функция setHeaderData() модели. Например:
- model->setHeaderData(0, Qt::Horizontal, QObject::tr( "ID" ));
- model->setHeaderData(1, Qt::Horizontal, QObject::tr( "Name" ));
- model->setHeaderData(2, Qt::Horizontal, QObject::tr( "City" ));
- model->setHeaderData(3, Qt::Horizontal, QObject::tr( "Country" ));
Заключение
В данной статье изложены базовые принципы работы с базами данных в Qt. Однако кроме указанных здесь возможностей еще много интересного, например, транзакции, работа с внешними ключами или создание дата-ориентированых форм. К сожалению эти темы достаточно обширны для одной статьи.
To access a database with QSqlQuery or QSqlQueryModel, create and open one or more database connections. Database connections are normally identified by connection name, not by database name. You can have multiple connections to the same database. QSqlDatabase also supports the concept of a default connection, which is an unnamed connection. When calling QSqlQuery or QSqlQueryModel member functions that take a connection name argument, if you don't pass a connection name, the default connection will be used. Creating a default connection is convenient when your application only requires one database connection.
Note the difference between creating a connection and opening it. Creating a connection involves creating an instance of class QSqlDatabase. The connection is not usable until it is opened. The following snippet shows how to create a default connection and then open it:
The first line creates the connection object, and the last line opens it for use. In between, we initialize some connection information, including the database name, the host name, the user name, and the password. In this case, we are connecting to the MySQL database flightdb on the host bigblue . The "QMYSQL" argument to addDatabase() specifies the type of database driver to use for the connection. The set of database drivers included with Qt are shown in the table of supported database drivers.
The connection in the snippet will be the default connection, because we don't pass the second argument to addDatabase(), which is the connection name. For example, here we establish two MySQL database connections named "first" and "second" :
After these connections have been initialized, open() for each one to establish the live connections. If the open() fails, it returns false . In that case, call QSqlDatabase::lastError() to get error information.
Once a connection is established, we can call the static function QSqlDatabase::database() from anywhere with a connection name to get a pointer to that database connection. If we don't pass a connection name, it will return the default connection. For example:
To remove a database connection, first close the database using QSqlDatabase::close(), then remove it using the static method QSqlDatabase::removeDatabase().
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers, which are derived from QSqlDriver. Alternatively, you can subclass your own database driver from QSqlDriver. See How to Write Your Own Database Driver for more information.
Create a connection (i.e., an instance of QSqlDatabase) by calling one of the static addDatabase() functions, where you specify the driver or type of driver to use (depending on the type of database) and a connection name. A connection is known by its own name, not by the name of the database it connects to. You can have multiple connections to one database. QSqlDatabase also supports the concept of a default connection, which is the unnamed connection. To create the default connection, don't pass the connection name argument when you call addDatabase(). Subsequently, the default connection will be assumed if you call any static member function without specifying the connection name. The following snippet shows how to create and open a default connection to a PostgreSQL database:
Once the QSqlDatabase object has been created, set the connection parameters with setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), and setConnectOptions(). Then call open() to activate the physical connection to the database. The connection is not usable until you open it.
The connection defined above will be the default connection, because we didn't give a connection name to addDatabase(). Subsequently, you can get the default connection by calling database() without the connection name argument:
QSqlDatabase is a value class. Changes made to a database connection via one instance of QSqlDatabase will affect other instances of QSqlDatabase that represent the same connection. Use cloneDatabase() to create an independent database connection based on an existing one.
Warning: It is highly recommended that you do not keep a copy of the QSqlDatabase around as a member of a class, as this will prevent the instance from being correctly cleaned up on shutdown. If you need to access an existing QSqlDatabase, it should be accessed with database(). If you chose to have a QSqlDatabase member variable, this needs to be deleted before the QCoreApplication instance is deleted, otherwise it may lead to undefined behavior.
If you create multiple database connections, specify a unique connection name for each one, when you call addDatabase(). Use database() with a connection name to get that connection. Use removeDatabase() with a connection name to remove a connection. QSqlDatabase outputs a warning if you try to remove a connection referenced by other QSqlDatabase objects. Use contains() to see if a given connection name is in the list of connections.
Some utility methods: | |
---|---|
tables() | returns the list of tables |
primaryIndex() | returns a table's primary index |
record() | returns meta-information about a table's fields |
transaction() | starts a transaction |
commit() | saves and completes a transaction |
rollback() | cancels a transaction |
hasFeature() | checks if a driver supports transactions |
lastError() | returns information about the last error |
drivers() | returns the names of the available SQL drivers |
isDriverAvailable() | checks if a particular driver is available |
registerSqlDriver() | registers a custom-made driver |
Note: When using transactions, you must start the transaction before you create your query.
On Windows 7 I installed qt creator and now I am trying to connect to the oracle database. I installed oracle client and plsql/developer and everything works fine. In qt creator I have error:
QsqlDatabase: QOCI driver not loaded
This qt documentation does not work for me. Is it clear tutorial how to do it on different platforms and situations?
4 Answers 4
Ok. I found solution.
set INCLUDE=%INCLUDE%;c:\oracle\oci\include
set LIB=%LIB%;c:\oracle\oci\lib\msvc
cd %QTDIR%\src\plugins\sqldrivers\oci
qmake oci.pro
nmake
If you are not using a Microsoft compiler, replace nmake with make in the line above.
but make or nmake didn't work for me. Because I have not installed Microsoft Visual c++ on my machine.
I made instruction how to do this:
At first don't forget to install qt sources. During the installation check Sources checkbox.
then download and install oracle client win32_11gR2_client.zip. choose Runtime option during installation.(even if you are using 64 bit os download 32 bit version on oracle client). It creates c:\app\user\product\client_1. directory
then open qt minGW command line(start ->all peograms -> qt[version] -> [version] -> MinGW [version] -> Qt [version] for Desktop MinGW [version]) and move to the oci source folder:
cd C:\Qt\Qt[version]\[version]\Src\qtbase\src\plugins\sqldrivers\oci
- then as documentation says include OCI(Oracle call interface) path and library:
set INCLUDE=%INCLUDE%;c:\app\user\product[version]\client_1\oci\include
set LIB=%LIB%;c:\app\user\product[version]\client_1\oci\lib\msvc
qmake oci.pro
mingw32-make
it will creates two .dll files for you qsqloci.dll(release version) and qsqlocid.dll(debug version)
- last step is to copy these two files into qtcreator installation folder. go to the:
C:\Qt\Qt[version]\[version]\Src\qtbase\plugins\sqldrivers
and copy these files into:
C:\Qt\Qt[version]\[version]\mingw[version]\plugins\sqldrivers
Читайте также: