Qt SQL Programming Partial translation

Source: Internet
Author: User
Tags readable

Introduction:QT SQL is one of the important modules of QT, for the sake of convenience, QT has a series of packages for SQL, and divides the SQL API into the following three layers:(1) drive layer(2) SQL API layer(3) User interface layerDirectory:first, the use of the premisesecond, the database classthird, connect to the database     · SQL Database DriverIv. executing SQL statements     · Data types for QT-supported database Systemsv. Using the SQL Model classFirst, the use of the premise: (1) in the C + + file to add the corresponding header file#include <QtSql>(2) Add QT SQL module to QT project fileQT + = SQLIi. database Class (1) The drive layer driver layer contains the following classes:Qsqldriver, Qsqldrivercreator, Qsqldrivercreatorbase, Qsqldriverplugin, and Qsqlresult.The driver layer builds an underlying bridge between the specific database system and the SQL API, which makes it irrelevant to the database, that is, QT treats various databases as an object, and the way to use them is to load them into the program via a driver plugin. We can understand that this database is available only if the QT version of the driver supports it. is the type of database that QT supports: (2) SQL API layer The main function of the collection of this class is to access the database, and the implication is the collection of method classes that perform various operations on the database. For example, you can useQsqldatabase to establish a connection through qsqlquery database interaction (query, etc.). In addition, several common classes are included: Qsqlerror, Qsqlfield, Qsqlindex, and Qsqlrecord. (3) The class of user interface layer of user interface layer includes:Qsqlquerymodel, Qsqltablemodel, and Qsqlrelationaltablemodel.They can be used to project data onto specific parts, and the part must have QT models and viewsModel/view frame. Note: Before you use the QT SQL class, you must instantiate the Qcoreapplication object. Third, connect to the database throughQsqlquery and Qsqlquerymodel accessing the database creates one or more database connections. database connections are distinguished by the database connection name [ConnectionName], not the database name [DatabaseName]. You can have multiple connections to the same number of libraries. In addition,Qsqldatabase supports the concept of the default connection, which is, of course, unnamed. When you call a member function with a connection name parameter of Qsqlquery or Qsqlquerymodel, the default connection is used if the connection name is not passed. Please note that there is a difference between creating a connection and opening the connection. Creating a connection creates athe Qsqldatabase object, and the connection is not available until this connection is opened. QT official gave an example: the first line creates a default database connection because the program does not pass a specific connection name as the second parameter to Adddatabase (), which can be modified as follows:"This creates a name for the"First" and "second two connections." It is worth mentioning that before opening the connection, the connection needs to be initialized, including:SetHostName (), Setdatabasename (), Setusername (), and SetPassword (). After the connection is initialized, it is possible to call Open () and, if open fails, returns false and the error message can be obtained by calling LastError (). In addition, after the connection is established, the call to database () returns the connection name, calls Close () before removing the connection, and then calls removedatabase () to remove it. Iv. Execute SQL statement execution queryThe Qsqlquery class provides an interface for executing SQL statements and queries, while Qsqlquerymodel and Qsqltablemodel provide an advanced interface for database operations. Before executing an SQL statement, you need to create aQsqlquery object, and then call qsqlquery::exec (), for example: The Qsqlqeury constructor allows you to receive an optional Qsqldatabase object that must be used by the database connection, and the database connection object is not passed in the previous example, so the default database connection will be taken. Operation Result setQsqlquery also provides access to the result set, after calling exec (), theinternal pointer of Qsqlquery will point to the first record in the result set, the first record can be obtained by calling next (), and then the next call ( ) to get the next record. In the following example, the effect is equivalent to traversing the result set: Qsqlqeury::value () returns the specified field value of the current record whose return value type is qvariant,qvariant is actually a union type, so it needs to be converted to the desired format (int/ Qstring/qbytearray, etc.). We can also putQsqlquery is seen as an iterator because it supports qsqlquery::next (), Qsqlquery::p revious (), Qsqlquery::first (), Qsqlquery::last (), and Qsqlquery::seek (). Qsqlquery::at () returns the row index of the current record, qsqlquery::size () returns the number of record bars for the result set, provided that qsqlquery::size () requires corresponding database-driven support. Insert, update, and deleteqsqlquery can execute arbitrary SQL statements, not limited to selects. such as inserting records: If you want to insert multiple records at the same time, you can use thebinding to do:Update a record or call a modified record, similar to inserting a record: Finally, delete the record: transaction processing if the underlying database engine supports transaction processing, thenqsqldriver::hasfeature (qsqldriver::transactions) returns True. You can initialize a transaction by calling Qsqldatabase::transactions (), and then you can perform an operation on the SQL statement, or call Qsqldatabase::commit () or Qsqldatabase::rollback (). It is important to note that transaction transaction must be started before query creation when using transaction processing.  As follows: Transactions can be used for data protection because their operations are atomic (such as querying foreign keys and creating records) and provide a set of rollback mechanisms. V. Use of SQL Model class in addition toQSQLQUERY,QT also provides three more advanced classes to access the database, which are Qsqlquerymodel, Qsqltablemodel, and Qsqlrelationaltablemodel. These classes derive from theQabstracttablemodel, and makes the data in the database easy to display in the view class, such as Qlistview and Qtableview. The SQL query model Qsqlquerymodel provides an SQL query-based read-only mode. Examples are: usingqsqlqeurymodel::setquery () After you set query, you can use qsqlquerymodel::record (int) to access individual records, or call Qsqlquerymodel: Data () or other methods that inherit from Qabstractitemmodel. The SQL table Model Qsqltablemodel provides a readable and writable model based on a simple SQL table.     The following example: Qsqltablemodel is a high-level alternative to qsqlquery, which can be used to browse and modify a single SQL table, and it does not require users to be familiar with the syntax of SQL. Use Qsqltablemodel::record () to retrieve a row of records in a table, Qsqltablemodel::setrecord () to modify Row Records. As shown in the following example: Of course, you can also use Qsqltablemodel::d ata () and Qsqltablemodel::setdata () to access the database. As shown in the following example: SetData (): Insert a record: Delete five consecutive records: After the record changes, the Qsqltablemodel::submitall () commit must be called to save, otherwise the data is not written. When and whether to call Qsqltablemodel::submitall () depends on the edit strategy (editing policy) of the table, the default editing strategy is Qsqltablemodel::onrowchange (accompanying changes), The other strategies are as follows: the SQL relational Table ModelQsqlrelationaltablemodel extended the Qsqltablemodel to provide support for foreign keys. A foreign key is a one-to-two mapping between a field in a table and a primary key field in another table. Table 1 is the use ofQsqltablemodel shows a table in Qtableview, while foreign key city and country have not yet been parsed into a readable value. Table 2 uses the Qsqlrelationaltablemodel to show that the outer key has been converted to a readable string value. The following code snippet shows the setup process for Qsqlrelationaltablemodel:

Ps:
This article translates into QT's SQL module, which is truncated in the middle, plus some personal understanding.
The entire QT SQL programming is not fully translated, and then there are two examples of QT, you can go to see for yourself.
Due to the limited English skills, there may be a number of improper translation, hope to point out, common progress.

http://blog.csdn.net/jan5_reyn/article/details/40164389

Qt SQL Programming Partial translation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.