QT Operations Database

Source: Internet
Author: User

Collate some of the key points of the QT operations database for future query learning (mainly the operation of MySQL).

First, to query whether the relevant driver has been installed, you can use the following program to verify:

#include <QtCore/QCoreApplication>

#include <QSqlDatabase>

#include <QDebug>

#include <QStringList>

int main (int argc, char *argv[])

{

Qcoreapplication A (argc, argv);

Qdebug () << "Available drivers:";

Qstringlist drivers = qsqldatabase::d rivers ();

foreach (QString driver, drivers)

Qdebug () << "/t" << driver;

return A.exec ();

}

The results are as follows:

Then connect to the database:

#include <QtGui/QApplication>

#include <QtGui>

#include <QtSql>

BOOL CreateConnection ()

{

Qsqldatabase db = Qsqldatabase::adddatabase ("Qmysql");

Db.setdatabasename ("test");

Db.setusername ("root");

Db.setpassword ("123456");

bool OK = Db.open ();

if (!ok) {

Qmessagebox::critical (0, QOBJECT::TR ("Connection database failed!!!" "), Db.lasterror (). text ());

return false;

}else{

Qmessagebox::information (0, Qobject::tr ("Tips"), QOBJECT::TR ("Connection database success!!!" "));

return true;

}

}

int main (int argc, char *argv[])

{

Qapplication A (argc, argv);

Qtextcodec *codec= qtextcodec::codecforname ("GB2312");

Qtextcodec::setcodecforlocale (codec);

Qtextcodec::setcodecforcstrings (codec);

QTEXTCODEC::SETCODECFORTR (codec);

if (!createconnection ())

return 1;

return A.exec ();

}

The results are as follows:

Insert operation:

//odbc How the database is represented

Qsqlquery query;
Query.prepare ("INSERT into student (ID, name)"
"VALUES (: ID,: Name)");
Query.bindvalue (0, 5);
Query.bindvalue (1, "sixth");
Query.exec ();

//oracle Presentation Mode

Query.prepare ("INSERT into student (ID, name)"
"VALUES (?,?)");
Query.bindvalue (0, 5);
Query.bindvalue (1, "sixth");
Query.exec ();

//  using Addbindvalue () function, omitting the number, which is assigned by attribute order

Query.prepare ("INSERT into student (ID, name)"
"VALUES (?,?)");
Query.addbindvalue (5);
Query.addbindvalue ("sixth");
Query.exec ();

//  using ODBC method, you can replace the number with the actual placeholder

Query.prepare ("INSERT into student (ID, name)"
"VALUES (: ID,: Name)");
Query.bindvalue (": id", 5);
Query.bindvalue (": Name", "sixth");
Query.exec ();

Note: Be sure to execute EXEC () at the end, otherwise the above statement will not be executed.

//  when multiple records are inserted, the bindings can be used for batch processing

Qsqlquery Q;
Q.prepare ("INSERT into student values (?,?)");

Qvariantlist ints;
INTs << << << << 13;
Q.addbindvalue (INTs);

Qvariantlist names;
Names << "Xiaoming" << "Xiaoliang" << "Xiaogang" << qvariant (qvariant::string);
The last one is an empty string, which should be the same as the previous format
Q.addbindvalue (names);

if (!q.execbatch ())//batch, output error if error occurs
Qdebug () << q.lasterror ();

Query operation:

//  return all properties and result sets

Qsqlquery query;
Query.exec ("SELECT * from student");//Perform a query operation
Qdebug () << "exec Next ():";
if (Query.next ())
Start with the next () function first, then query points to the first record in the result set
{
int rowNum = query.at ();
Gets the number of the record that the query points to in the result set
int columnnum = Query.record (). Count ();
Get the number of attributes (that is, columns) in each record
int fieldno = Query.record (). IndexOf ("name");
Gets the number of the column that contains the Name property, the column is numbered from left to right, and the leftmost number is 0
int id = query.value (0). ToInt ();
Gets the value of the id attribute and converts it to type int
QString name = Query.value (Fieldno). toString ();
Gets the value of the Name property
Qdebug () << "RowNum is:" << rowNum//outputs the result
<< "ID is:" << ID
<< "name is:" << name
<< "Columnnum is:" << columnnum;
}
Qdebug () << "exec Seek (2):";
if (Query.seek (2))
Navigate to the record numbered 2 in the result set, which is the third record because the first record is numbered 0
{
Qdebug () << "RowNum is:" << query.at ()
<< "ID is:" << query.value (0). ToInt ()
<< "name is:" << query.value (1). ToString ();
}
Qdebug () << "exec Last ():";
if (Query.last ())
Navigate to the last record in the result set

{
Qdebug () << "RowNum is:" << query.at ()
<< "ID is:" << query.value (0). ToInt ()
<< "name is:" << query.value (1). ToString ();
}

The result set is actually a collection of all the records that were queried, and in the Qsqlquery class, several functions are provided to manipulate the collection, and it is important to note that the records in this collection are from 0 start numbering. The most commonly used are:

Seek (int n) : query points to the nth record of the result set.

First () : query points to a record in the result set.

Last () : Query points to the final record of the result set.

Next () : query points to the next record, and each time the function is executed, it points to the next record in the adjacent line.

Previous () : Query points to the previous record, and each time the function is executed, it points to the previous record.

Record () : Gets the records pointed to now.

value (int n) : Gets the value of the property. where n represents the nth attribute of your query, for example, above we use "SELECT * from student" equivalent to "SELECT ID, name from student", then value (0) returns the values of the id attribute, and value (1) returns n The value of the Ame property. The function returns data of type Qvariant, and for the corresponding relationship of that type to other types, you can view qvariant in Help.

At () : Gets the number of the record in the result set that the query points to now.

Need to be explained when the Query.exec ("SELECT * FROM student") has just finished executing; When this line of code, query is pointing to the result set, we can take advantage of query.next (), when the first execution of this code, query points to the first record of the result set. Of course, we can also use the Seek (0) function or the first () function to point the query to a result set of record one. However, in order to save memory overhead, the recommended method is to Query.exec ("SELECT * from student"); This line of code is preceded by Query.setforwardonly (true); This code can then only use the next () and Seek () functions.

//  a result set satisfying certain conditions, method one

Qsqlquery query;
Query.prepare ("Select name from student where id =?");
int id = 2; Gets the value of the ID from the interface
Query.addbindvalue (ID); Bind the ID value
Query.exec ();
Query.next (); Point to First record
Qdebug () << query.value (0). toString ();

//  Method Two

Qsqlquery query;

Query. EXEC (Qobject:: TR ("SELECT * from student where id =%1"). Arg (2));

if (! query. Next ())

Qdebug () << "None";

Else

Qdebug () << query. Value (0). ToInt () << query. Value (1). ToString ();

A transaction is an important function of a database, so-called transactions are user-defined sequences of database operations that either do it all or do nothing and are an inseparable unit of work. Start a transactional operation in Qt with transaction () and end with the commit () function or the rollback () function. Commit () represents the commit, which commits all the operations of the transaction. Specifically, all updates to the database in a transaction are written back to the database, and the transaction ends normally. Rollback () indicates a rollback, that is, a failure occurred during the operation of the transaction, the transaction cannot proceed, and the system revokes all completed operations on the database in the transaction, rolling back to the state at the beginning of the transaction.

Qsqlquery query;
if (qsqldatabase::d atabase (). Transaction ())//Start transaction operation
{
Perform various database operations below
Query.exec ("INSERT into student values (+, ' hello ')");
Query.exec ("Delete from student where id = 1″);
//
if (! Qsqldatabase::d atabase (). commit ())
{
Qdebug () << qsqldatabase::d atabase (). LastError (); Submit
if (! Qsqldatabase::d atabase (). Rollback ())
Qdebug () << qsqldatabase::d atabase (). LastError (); Rolling back
}
}
Output whole Sheet
Query.exec ("SELECT * from student");
while (Query.next ())
Qdebug () << query.value (0). ToInt () << query.value (1). ToString ();

Qt uses its own mechanism to avoid the use of SQL statements, which provides us with a simpler database operation and data display model. They are read-only Qsqlquerymodel, manipulate the Qsqltablemodel of a single table and Qsqlrelationaltablemodel that can support foreign keys

Qsqlquerymodel

Qsqlquerymodel *model = new Qsqlquerymodel;
Model->setquery ("SELECT * from student");
Model->setheaderdata (0, Qt::horizontal, tr ("id"));
Model->setheaderdata (1, qt::horizontal, tr ("name"));
Qtableview *view = new Qtableview;
View->setmodel (model);
View->show ();

Qsqltablemodel

Qsqltablemodel *model;

Model = new Qsqltablemodel (this);
Model->settable ("Student");
Model->seteditstrategy (Qsqltablemodel::onmanualsubmit);
Model->select (); Select all rows for the entire table
Model->removecolumn (1); The Name property column is not displayed, and if you add a record at this point, the value of the property is not added
Ui->tableview->setmodel (model);
Ui->tableview->setedittriggers (qabstractitemview::noedittriggers); Make it non-editable

//  Filter

Model->setfilter (qobject::tr ("name = '%1′"). Arg (name)); Filter by name
Model->select (); Show results

//  Delete Operation

Int currow = Ui->tableview->currentindex (). row ();  
    //  Gets the selected row  
Model->removerow (currow);  
    //  Delete the row  
int ok = Qmessagebox:: Warning (this,tr (  "Delete current line! "), tr (  "You are OK  "
                                                               "Delete the current line?"    ),
                          qmessagebox::yes,qmessagebox::no);
if (ok = = Qmessagebox::no)
{ 
       model->revertall ();//   Revoke   if not deleted;
} 
Else

Model->submitall (); Otherwise commits, deletes the row in the database

//  Insert Operation

int rowNum = Model->rowcount (); Get the number of rows in a table
int id = 10;
Model->insertrow (RowNum); Add a row
Model->setdata (Model->index (rownum,0), id);

Model->submitall ();//Remember to submit

Qsqlrelationaltablemodel

//  CREATE TABLE student (ID int primary key, name Vchar,course int)

CREATE TABLE course (ID int primary key, name Vchar, teacher Vchar)

Model = new Qsqlrelationaltablemodel (this);
Model->seteditstrategy (Qsqltablemodel::onfieldchange); Write to database when property changes
Model->settable ("Student");
Model->setrelation (2,qsqlrelation ("course", "id", "name"));
Set the third property of the student table to the foreign key of the ID property of the course table and display it as the value of the course table's Name property
Model->setheaderdata (0, Qt::horizontal, qobject::tr ("ID"));
Model->setheaderdata (1, Qt::horizontal, Qobject::tr ("Name"));
Model->setheaderdata (2, Qt::horizontal, Qobject::tr ("Course"));
Model->select ();
Ui->tableview->setmodel (model);

Ui->tableview->setitemdelegate (New Qsqlrelationaldelegate (Ui->tableview));//If the user changes the course properties, Then he can only choose among the courses in the curriculum and not fill in the course. The Qsqlrelationaldelegate delegate class in QT can implement this function. We just need to add one line of code

This article is based on the information on the http://hi.baidu.com/yafeilinux/.

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.