Detailed description of database operations in QT

Source: Internet
Author: User

QTMediumDatabaseThe related operations are described in this article.QTMediumDatabaseOperations, the article is very detailed aboutDatabaseFor details, see the content.

Database Operations

1. MySql driver Compilation

In windows, MySql driver compilation in mingw, MySql5, and Qt4 mainly involves the following steps:

(1) download http://www.qtcn.org/download/mingw-utils-0.3.tar.gz
;
(2gz decompress mingw-utils-0.3.tar.gz and copy the reimp tool in the bin directory to the bin in the mingw directory. If Dev-C ++ is used, copy it to the C: \ Dev-Cpp \ bin directory.

(3) copy the include and lib directories in the MySql installation directory to a path without spaces, such as C: \ mysql;

(4) Open Qt Command Prompt and execute the following commands respectively:

Cd c: \ mysql \ lib \ opt reimp-d libmysql. lib dlltool-k-d libmysql. def-l libmysql.

In this way, a libmysql. a file is generated under the c: \ mysql \ lib \ opt directory;

(5) run the following command:

 
 
  1. cd %QTDIR%\src\plugins\sqldrivers\mysql   
  2.  
  3. qmake -o Makefile "INCLUDEPATH+=C:\MYSQL\INCLUDE" "LIBS+=C :\MYSQL\LIB\OPT\LIBMYSQL.a" mysql.pro  

Find the Makefile under % QTDIR % \ src \ plugins \ sqldrivers \ mysql. release and Makefile. debug file, remove the-llibmysql item and make the compilation. libqsqlmysql is generated under the % QTDIR % \ plugins \ sqldrivers directory. a, qsqlmysql. dll files, and then in the program's. add QT + = SQL to the pro file and include # include at the beginning of the program to operate the database.

2. Completely solves the problem that the database stores Chinese characters and Qt programs display Chinese and Chinese strings in the database.

(1) varchar, char, text, and other character-related fields in the database and table must be used in gbk_chinese_ci mode. If this method is not used, it saves a lot of trouble.

(2) To re-compile the MySQL driver of Qt, modify the src/SQL/drivers/mysql/qsql_mysql.cpp file. The part to be modified is as follows: the codec function of the 108th line

 
 
  1. Static QTextCodec * codec (MYSQL * mysql)
  2. {
  3. Return QTextCodec: codecForName ("GBK"); // Add part
  4. # If MYSQL_VERSION_ID >=32321
  5. QTextCodec * heuristicCodec = QTextCodec: codecForName (mysql_character_set_name (mysql ));
  6. If (heuristicCodec)
  7. Return heuristicCodec;
  8. # Endif
  9. Return QTextCodec: codecForLocale ();
  10. }

(3) then, re-compile the mysql driver of qt and add the following three sentences at the beginning of the app in the main function of the Qt program. Adding these three statements saves unnecessary trouble.

 
 
  1. QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));   
  2. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));   
  3. QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));  

(4) After connecting to the Qt database, run the "set names 'utf8'" statement or "set names 'gbk '".

 
 
  1. db = QSqlDatabase::addDatabase("QMYSQL");   
  2. db.setHostName("localhost");   
  3. db.setDatabaseName("yourdatabase");   
  4. db.setUserName("yourusername");   
  5. db.setPassword("yourpassword");   
  6. db.open();   
  7. db.exec("SET NAMES ’UTF8’");  

After the above four steps, you can directly use a Chinese string in the Qt program, and can directly use a Chinese string between the program and the database.

3. Connect to the MySql database

 
 
  1. QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");   
  2. db.setHostName("localhost");   
  3. db.setDatabaseName("test");   
  4. db.setUserName("root");   
  5. db.setPassword("******");   
  6. bool ok = db.open(); 

Link to the QSLite database:

 
 
  1. QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");  

4. SELECT Operation

 
 
  1. QSqlQuery query;
  2. Int numRows;
  3. Query.exe c ("SELECT * FROM scores order by id ASC ");
  4. While (query. next ())
  5. {
  6. QString name = query. value (0). toString (); // The query. value () parameter can only be index
  7. Int salary = query. value (1). toInt ();
  8. Label = setText (QString: number (salary) + name); // test the number of rows queried
  9. If (db. driver ()-> hasFeature (QSqlDriver: QuerySize ))
  10. {
  11. NumRows = query. size ();
  12. }
  13. Else
  14. {
  15. // This can be very slow
  16. Query. last ();
  17. NumRows = query. at () + 1;
  18. }
  19. }

5. INSERT operation

1) insert a record directly)

 
 
  1. QSqlQuery query;   
  2. query.exec("INSERT INTO employee (id, name, salary) VALUES (1001, ’Thad Beaumont’, 65000)");  

2) perform the ": Field" Operation

 
 
  1. QSqlQuery query;   
  2. query.prepare("INSERT INTO employee (id, name, salary) VALUES (:id, :name, :salary)");   
  3. query.bindValue(":id", 1001);   
  4. query.bindValue(":name", "Thad Beaumont");   
  5. query.bindValue(":salary", 65000);   
  6. query.exec();  

(3) pass "?" Operation

 
 
  1. QSqlQuery query;   
  2. query.prepare("INSERT INTO employee (id, name, salary) VALUES (?, ?, ?)");   
  3. query.addBindValue(1001);   
  4. query.addBindValue("Thad Beaumont");   
  5. query.addBindValue(65000);   
  6. query.exec();  

6. UPDATE operations

 
 
  1. QSqlQuery query;   
  2. query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");  

7. DELETE operation

 
 
  1. QSqlQuery query;   
  2. query.exec("DELETE FROM employee WHERE id = 1007");  

8. transaction () Operation

Sometimes QSqlDatabase: transaction () can speed up a series of complex operations.

 
 
  1. // The database is a QSqlDatabase object.
  2. If (database. driver ()-> hasFeature (QSqlDriver: Transactions) // test whether the database supports Transactions,
  3. {
  4. Database. transaction ();
  5. Query.exe c ("SELECT name FROM scores WHERE id = 19 ");
  6. If (query. next ())
  7. {
  8. // Str = query. value (0). toString ();
  9. Str = "China ";
  10. Query.exe c ("insert into scores (name) VALUES ('" + str + "')");
  11. }
  12. Database. commit ();
  13. }

NOTE: If str is a Chinese string, 'str' must be enclosed in single quotation marks in SQL statements, no single quotation marks are allowed (it refers to the SQL statement included in double quotation marks)

9. Use the SQL Model class

 
 
  1. QSqlQueryModel-a read-only model for reading database data
  2. QSqlTableModel-a single table model that can be read and written without the need to write SQL statements
  3. QSqlRelationalTableModel -- a subclass of QSqlTableModel

These classes all inherit from qiniacttablemodel, and they all inherit from qiniactitemmodel.

1) Use of QSqlQueryModel

 
 
  1. QSqlQueryModel querymodel;
  2. Querymodel. setQuery ("SELECT * FROM scores order by id ASC ");
  3. For (num = 0; numquerymodel. rowCount (); num ++)
  4. {
  5. Str + = QString: number (querymodel. record (num). value ("id"). toInt ());
  6. Str + = "";
  7. Str + = querymodel. record (num). value ("name"). toString ();
  8. // Note that the value () parameter can be an index or a field name. The value () parameter of the preceding QSqlQuery can only be an index.
  9. Str + = "\ n ";
  10. }
  11. Label-> setText (str );

2) Use of QSqlTableModel

① Read data

 
 
  1. QSqlTableModel tablemodel;  
  2.  
  3. tablemodel.setTable("scores");   
  4. tablemodel.setFilter("id > 10");   
  5. tablemodel.setSort(0,Qt::DescendingOrder);   
  6. tablemodel.select();   
  7. for (num=0;numtablemodel.rowCount();num++)   
  8. {   
  9. str += QString::number(tablemodel.record(num).value("id").toInt());   
  10. str += " ";   
  11. str += tablemodel.record(num).value(1).toString();   
  12. str += "\n";   
  13. }   
  14. label->setText(str);  

② Modify data

 
 
  1. QSqlTableModel tablemodel;
  2. Tablemodel. setTable ("scores ");
  3. Tablemodel. setFilter ("id> 10 ");
  4. Tablemodel. setSort (0, Qt: DescendingOrder );
  5. Tablemodel. select ();
  6. For (num = 0; numtablemodel. rowCount (); num ++)
  7. {
  8. QSqlRecord record = tablemodel. record (num );
  9. Record. setValue ("name", record. value ("name"). toString () + "2 ");
  10. Tablemodel. setRecord (num, record );
  11. }
  12. If (tablemodel. submitAll ())
  13. Label-> setText ("modified successfully! ");
  14. Else
  15. Label-> setText ("modification failed! ");
  16. Or you can use setData () to modify the Code as follows:
  17. QSqlTableModel tablemodel;
  18. Tablemodel. setTable ("scores ");
  19. Tablemodel. setFilter ("id> 10 ");
  20. Tablemodel. setSort (0, Qt: DescendingOrder );
  21. Tablemodel. select ();
  22. Tablemodel. setData (tablemodel. index (2, 1), "data modification ");
  23. If (tablemodel. submitAll ())
  24. Label-> setText ("modified successfully! ");
  25. Else
  26. Label-> setText ("modification failed! ");

③ Delete data

 
 
  1. Tablemodel. removeRows (row, 5 );
  2. // RemoveRows () the first parameter is the number of rows in the first row to be deleted, and the second parameter is the total number of rows to be deleted;
  3. Tablemodel. submitAll ();
  4. // Note: Use QSqlTableModel to modify or delete data, and use submitAll () to execute the change.

④ Insert data

 
 
  1. QSqlRecord record = tablemodel. record ();
  2. Record. setValue ("name", "inserted ");
  3. Tablemodel. insertRecord (2, record );
  4. // Note: insert the insertRecord function here. The first parameter of this function is the row number inserted to tablemodel,
  5. The second parameter is record. Note that the record here must match the record in tablemodel,
  6. Therefore, QSqlRecord record = tablemodel. record (); in addition, submitAll is not required for the insert operation. Because, insertRecord), bool value is returned.

10. Use QTableView

# Include

 
 
  1. QTableView *view = new QTableView();   
  2. view->setModel(&model);   
  3. view->setEditTriggers(QAbstractItemView::NoEditTriggers);   
  4. view->show(); 

Summary: DetailsQTMediumDatabaseThe related operations have been introduced. I hope this article will help you!

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.