Qt DatabaseLink and how to useSQLIs the content to be introduced in this article, mainly to learnQTMediumDatabaseAndSQLFor more information about how to use it, see this article.
I have never been in touch with the database. I suddenly had the opportunity to use MySQL for the first time. I just learned SQL syntax and learned how to use Qt in combination with the database, by the way, I tried to connect the database to Qt and use SQL. I won't talk about the SQL part, and Qt will talk about the link part first.
1. database-driven first
Now, Qt SDk for release converts LibMySQL. lib in MySQL/opt to. a. You can skip this step by using MSVC ). Then go to qt/src/plugins/sqldriver/mysql to compile the driver.
- QMAKE -o Makefile "INCLUDEPATH+=MYSQL/INCLUDE" "LIBS+=MYSQL/LIB/OPT/libmysql.a" mysql.pro
Pay attention to the qmake parameter and make it again. This part is described in detail on the Internet,
2. Use SQL in Qt
Mainly the following classes
QSqlDatabase is built on the Database Link
QSqlQuery is used to execute SQL statements.
QSqlTableModel combined with QTableView can output database tables
Paste the simple Demo I wrote
- QSqlDatabase db = QSqlDatabase: addDatabase ("QMYSQL"/* "QODBC" */); // becomes the new default connection
- Db. setUserName ("root"); // User Name
- Db. setPassword ("password"); // password
- Db. setHostName ("localhost ");
- Db. setDatabaseName ("test"); // Database Name
- Db. setConnectOptions ("CLIENT_SSL = 1; CLIENT_IGNORE_SPACE = 1"); // use SSL
- Db. setPort (3306); // Port
- If (db. open ()){
- QDebug () <"open/n" <db. lastError (). driverText () <"/n ";
- }
- Else {
- QDebug () <"open faile/n ";
- }
- QSqlQuery query; // used to execute the SQL language
- Query.exe c ("show databases"); // very convenient
- While (query. next ()){
- QDebug () <query. value (0). toString () <"/n ";
- }
-
- QSqlTableModel * model = new QSqlTableModel; // indirectly load the database table into QTableView
- Model-> setTable ("people"); // table name
- Model-> setEditStrategy (QSqlTableModel: OnManualSubmit );
- Model-> select ();
- // Model-> removeColumn (0); // don't show the ID
- // Model-> setHeaderData (0, Qt: Horizontal, QObject: tr ("ID "));
- Model-> setHeaderData (0, Qt: Horizontal, tr ("Name "));
- Model-> setHeaderData (1, Qt: Horizontal, tr ("Age "));
- Model-> setHeaderData (2, Qt: Horizontal, tr ("Sex "));
-
- QTableView * view = new QTableView (this );
- View-> setModel (model );
- Db. close ();
- QGridLayout * gl = new QGridLayout ();
- Gl-> addWidget (view );
- This-> setLayout (gl );
Summary: DetailsQt DatabaseLink and how to useSQLI hope this article will help you!