Sql_interface.h
#ifndef sql_interface_h Span class= "Hljs-preprocessor" >#define sql_interface_h class Modcat{public : int mod_cat_id; QString name;}; Class Sqlclass: public qobject{q_objectprivate : qsqldatabase* db; public : sqlclass (qobject* parent = NULL); virtual ~sqlclass (); public : bool config _database (); bool query_mod_cat (qlist<modcat>& result);}; #endfi//
This defines a class modcat, which is used primarily to store data obtained from the database.
The Query_mod_cat parameters we define use Qlist to store every single piece of our data.
Sql_interface.cpp
#define DATA_base_name"Db_conn_da_lib"Sqlclass::Sqlclass (qobject* Parent): Qobject (parent) {}bool Sqlclass::Config_database () {db = &qsqldatabase::Adddatabase ("Qodbc"DatA_base_name);Db->sethostname ("XX");Db->setdatabasename ("Driver={sql SERVER}; Server=xx;database=da_lib ");Db->setusername ("");Db->setpassword ("123456"); return true;}bool Sqlclass::Query_mod_cat (qlist<modcat>& result) {qsqldatabase db_conn = qsqldatabase::Database (DATA_base_name,true); if(!db_conn.open ()) {qdebug () << db_conn.lasterror (). Text ();}qsqlquery query = qsqlquery::Qsqlquery (Db_conn);Query.prepare ("Select Id,name from VIEW ORDER by name ASC"); if(Query.exec ()) { while(Query.next ()) {Modcat VO;vo.mod_cat_id = Query.value (0). ToInt ();Vo.name = Query.value (0). TOSTIRNG ();Result.append (VO);} db_conn.close (); return true;}Else{Db_conn.close ();Qdebug () <<qstring ("Failed to query the MoD cat,error:") <<query.lasterror (). Text (); return false;}}Sqlclass::~sqlclass () {}
Config_database () is my function to configure the connection, and in Adddatabase () The data_base_name represents the name of the connection, which is to work with the database operation function.
In the function Query_mod_cat ()
Qsqldatabase db_conn = qsqldatabase::d atabase (data_base_name,true);
A DB that represents the operation of the database when the name is Data_base_name.
For a description of the function database, you can view the QT Assistant.
Many times we may open the default connection, then may produce different db operation and error, this time to determine the connection name of the query operation is very necessary.
Qt Database Learning Record