Linux Platform QT database programming (from Network)

Source: Internet
Author: User
Tags prepare sqlite database

Linux Platform QT Database Programming

In the Linux platform using QT to write GUI programs, in the database programming, there are two options, namely: Linux platform-based database interface function programming, the other is the use of QT comes with the relevant database classes. Well, here I'll take a look at the implementation of these two methods separately.

One, the database interface programming using the Linux platform:

Here I am using a free database SQLite, from the network of the next sqlite-3.0.8.tar.gz source package, and then install, installed, you can use it to provide the function interface. Next we use the installed SQLite provided function interface, used in Qt, the code snippet example is as follows:

This is a slot function, which implements the operation of the database, using the API functions provided by the SQLite database that was just installed.

void Qt1::open_data ()

{

int ret;

Char *zerrmsg;

Open the database, and if the database file does not exist, create it

ret = Sqlite3_open ("student.db", &db);

if (ret)

{

fprintf (stderr, "Cannot open database:%s\n", sqlite3_errmsg (db));

Sqlite3_close (DB);

Exit (-1);

}

Else

{

printf ("You are right\n");

}

SQL statements

Char *sql = (char *) "CREATE TABLE studentdata (\

ID INTEGER PRIMARY key,\

SID tnteger,\

Name VARCHAR (20), \

Score Integer\

);";

Using the C interface to execute one of the above SQL statements, create a table

Sqlite3_exec (DB,SQL,0,0,&ZERRMSG);

}

Here just give a simple example, through those SQL statements, and then with the operation of SQLite provided by the interface function, we can add to the database, delete, change, check and so on this series of operations. Of course, when compiling the note is to be sure to connect such a SQLite database dynamic library, otherwise it is compiled.

Second, the use of QT-band database programming classes:

In Qt, a module such as Qtsql is provided, which provides an interface to the SQL database that is independent of the platform and the type of database, which is supported by a set of classes that use QT's model/view architecture to integrate the database with the user interface. Qsqldatabase Objects characterize the association of databases, and QT uses drivers to communicate with the application programming interfaces of various databases. QT supports a variety of databases, but most of the database is charged, QT provides a built-in database, that is SQLite.

So here we will use the operation interface provided by QT to operate on the database, the code example is as follows:

Header file Data.h

#ifndef _data_

#define _data_

#include <QDialog>

#include <QString>

#include <QSqlQuery>

#include <QSqlDatabase>

#include "Ui_data.h"

Class Data:public Qdialog, public ui_data

{

Q_object

Public

Data (Qwidget *parent = 0);

void Creatdata ();

Public Slots:

void Datainsert ();

void Dataselete ();

Private

Qsqldatabase DB; A built-in Qsqldatabase object that can be associated with a database

Qsqlquery *query; Qsqlquery provides a number of interfaces that can be used to process data sources

};

#endif

/****************************************************************/

Implementing File Data.cpp

/****************************************************************/

#include <QDebug>

#include <QSqlError>

#include <QStringList>

#include <QTableWidgetItem>

#include "Data.h"

Data::D ata (Qwidget *parent): Qdialog (parent)

{

SETUPUI (this);

Creatdata (); Create a database file

Connect (Pbinsert, SIGNAL (clicked ()), this, SLOT (Datainsert ()));

Connect (Pbselete, SIGNAL (clicked ()), this, SLOT (Dataselete ()));

Connect (Pbquit, SIGNAL (clicked ()), this, SLOT (Close ()));

}

void Data::creatdata ()

{

Create a Qsqldatabase object, the first parameter of the Adddatabase function specifies the QT

Which database driver must be used to access this database

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

Db.sethostname ("Linux");

Set the name of the database file

Db.setdatabasename ("database");

Set User name

Db.setusername ("Steve");

Set Password

Db.setpassword ("Steve");

Open the database file

bool OK = Db.open ("Steve", "Steve");

if (OK)

{

Qdebug () << "You is Right";

}

Specifies that DB is the parent class for query

query = new Qsqlquery (db);

Create a table

Query->exec ("CREATE TABLE data (\

ID INTEGER PRIMARY KEY autoincrement,\

Name VARCHAR (6) Not null,\

Score VARCHAR (not NULL); ");

Query->clear ();

}

void Data::d atainsert ()

{

QString name = Lename->text ();

QString score = Lescore->text ();

Qdebug () <<name<< ":" <<score;

/* Prepares the SQL query query for execution. Returns true if the query is prepared successfully; otherwise returns false.*/

Use Prepare () to specify a query that contains placeholders.

Then assign the value to bind the data you want to insert

Query->prepare ("INSERT into data (name, score) VALUES (: Name,: Score)");

Query->bindvalue (": Name", Name.tolocal8bit (). data ());

Query->bindvalue (": Score", Score.tolocal8bit (). data ());

Query->exec (); Execute SQL statement

Query->clear ();

}

void Data::d ataselete ()

{

Tablewidget->setrowcount (10);

Tablewidget->setcolumncount (2);

Tablewidget->sethorizontalheaderitem (0, New Qtablewidgetitem ("Name"));

Tablewidget->sethorizontalheaderitem (1, New Qtablewidgetitem ("score"));

Query->exec ("SELECT * from data");

int i = 1;

int j = 0;

As soon as you call next () for the first time, you can position the qsqlquery to the first record in the result set.

Then call next (), which moves the record pointer forward one record at a time until the end returns false.

while (Query->next ())

{

Value (i) returns the field value as Qvariant.

QString name = Query->value (i++). toString ();

Tablewidget->setitem (J, I-2, New Qtablewidgetitem (name));

QString score = Query->value (i). toString ();

Tablewidget->setitem (j + +, I-1, new Qtablewidgetitem (score));

i = 1;

}

Query->clear ();

}

Through the above code, the effect is as follows:

If you want to use the Qtsql module, you must also include a statement in the Pro file: QT + = sql

Here are some of the classes about QT for database operations:

Qsqldatabase qsqldriver qsqlquery qsqlerror Qsqlquerymodel

Qsqltablemodel qsqlrelation Qsqlrelationaltablemodel

Summarize:

In the use of QT GUI programming, if it is the operation of the database, then you can use two methods, but for QT itself, or use QT own Qtsql module to operate or better, through the QT own some of the classes to operate these databases, not using the Linux platform under the interface trouble.

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.