Detailed steps for QT to connect to MYSQL database

Detailed steps for QT to connect to MYSQL database

The first step is to add the corresponding database module (sql) to the project file ( .pro ) and introduce several classes (also the corresponding header files)

  • QSqlError class that provides SQL database error information
  • QSql Query provides methods for executing and manipulating SQL statements
  • QSql QueryDatabase handles the connection to the database

1. Database connection

 //Add MySQL database QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL"); 
        //Connect to database db.setHostName("127.0.0.1"); //Database server IP
        db.setUserName("root"); //Database username db.setPassword("root"); //Database username and password db.setDatabaseName("sys"); //Database name if(db.open()==false)
        {
            QMessageBox::information(this,"Database open failed",db.lastError().text());
            return;
        }

If it fails, it may be that QT needs a library to connect to the MySQL database (download libmysql.dll yourself) and put the library file in the QT installation directory D:\Qt\5.9\mingw53_32\bin (according to your own directory). My QT version is 5.9. Is the database open? Is the user wrong? Does this database exist?

2. Create a table

QSqlQuery q;
q.exec("create table student(id int primary key auto_increment, name varchar(255), age int, score int)ENGINE=INNODB;");

3. Insert data into the table

Method 1 (Single row insert)

q.exec("insert into student(id, name, age,score) values(1, '张三', 24,80);");

Method 2 (multi-row insert) is divided into ODBC style and Oracle style

1. ODBC style

 q.prepare("insert into student(name, age,score) values(?, ?, ?)"); //? is a placeholder QVariantList name;
   name<<"prime number"<<"waiting"<<"An An";
   QVariantList age;
   age<<-2<<12<<14;
   QVariantList score;
   score<<0<<89<<90;
   //Bind the corresponding values ​​to the fields in order q.addBindValue(name);
   q.addBindValue(age);
   q.addBindValue(score);
   //Execute preprocessing commands q.execBatch();

To add #include<QVariantList> header file, the fields should be bound in order

2.orace style d

//Placeholder: + custom name q.prepare("insert into student(name, age,score) values(:n, :a,:s)");
  QVariantList name;
  name<<"Quark"<<"Redmi"<<"Hongmeng";
  QVariantList age;
  age<<5<<10<<3;
  QVariantList score;
  score<<77<<89<<99;
  // Bind the fields in any order because of: + custom name q.bindValue(":n",name);
  q.bindValue(":s",score);
  q.bindValue(":a",age);
  //Execute preprocessing commands q.execBatch();

The order of fields can be arbitrary due to the placeholder distinction

3. Update table

QSqlQuery q;
        q.exec("update student set score=76 where name='李四'");

4. Delete the table

QSqlQuery q;
        q.exec("delete from student where name='张三'");

5. Traverse the table

QSqlQuery q;
    q.exec("select *from student");
    while(q.next()) // false after traversal
    {
        //With subscript //qDebug()<<q.value(0).toInt()<<q.value(1).toString()<<q.value(2).toInt() 
        <<q.value(3).toInt();
        //With field qDebug()<<q.value("id").toInt()<<q.value("name").toString()<<q.value("age").toInt() 
        <<q.value("score").toInt();
    }

This is the end of this article about QT connecting to MYSQL database. For more relevant content about QT connecting to MYSQL database, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use QtSql to connect to MySql database in PyQt
  • How to use Qt to connect to MySQL database under ubuntu linux
  • Python3+PyQt5 database programming--add, delete and modify examples
  • python3+PyQt5 using database table view
  • python3+PyQt5 using database window view

<<:  Summary of CSS gradient effects (linear-gradient and radial-gradient)

>>:  Getting Started Tutorial for Beginners: Domain Name Resolution and Binding

Recommend

How to configure NAS on Windows Server 2019

Preface This tutorial installs the latest version...

How to introduce pictures more elegantly in Vue pages

Table of contents Error demonstration By computed...

MySQL isolation level detailed explanation and examples

Table of contents 4 isolation levels of MySQL Cre...

Ajax responseText parses json data case study

Solve the problem that the responseText returned ...

Explanation of the working principle and usage of redux

Table of contents 1. What is redux? 2. The princi...

How to implement JavaScript's new operator yourself

Table of contents Constructor new Operator Implem...

JavaScript adds event listeners to event delegation in batches. Detailed process

1. What is event delegation? Event delegation: Ut...

Example code of how CSS matches multiple classes

CSS matches multiple classes The following HTML t...

How to implement the builder pattern in Javascript

Overview The builder pattern is a relatively simp...

Web project development JS function anti-shake and throttling sample code

Table of contents Stabilization Introduction Anti...

How to Fix File System Errors in Linux Using ‘fsck’

Preface The file system is responsible for organi...

JS implements simple example code to control video playback speed

introduction I discovered a problem before: somet...

Detailed explanation of SQL injection - security (Part 2)

If there are any errors in this article or you ha...