qt连接MySql数据库及增删改查示例

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QtSql/QSqlDatabase"
#include "QMessageBox"
#include "qdebug.h"
#include 
#include 
#include 
#include 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
 
  
MainWindow::~MainWindow()
{
    delete ui;
}
 
  
void MainWindow::on_pushButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
        db.setHostName("127.0.0.1");
        db.setPort(3306);
        db.setDatabaseName("MyDataBaseName"); //不是Database,记得别填错
        db.setUserName("root");
        db.setPassword("root");
        bool ok = db.open();
        if (ok){
            QMessageBox::information(this, "infor", "link success");
        }
        else {
            QMessageBox::information(this, "infor", "link failed");
            qDebug()<<"error open database because"< 
  
        }
 
  
 
  
}
 
  
void MainWindow::on_pushButton_2_clicked()
{
    QSqlQuery query;
    QString sql1 = "create table ChannelValues1(id int ,name varchar(100),Ch1 double(64,5),Ch2 double(64,5));";
    query.exec(sql1);
}
 
  
void MainWindow::on_pushButton_3_clicked()
{
    QTime time;
    time.start();
    for(int i=0;i<500*10000;i++)
    {
        int id = 0;
        QString name = "aaa";
        double Ch1 = 9.999;
        double Ch2 = 8887.987666652;
        QString sql = QString("insert into ChannelValues1(id,name,Ch1,Ch2) values('%1','%2','%3','%4')").arg(id).arg(name).arg(Ch1).arg(Ch2);
        QSqlQuery query;
        query.exec(sql);
    }
  qDebug()<<"耗时"+time.elapsed()<<"毫秒";
}
 
  
void MainWindow::on_pushButton_4_clicked()
{
      int id =0;
       QString sql = QString("delete from ChannelValues1 where id = '%1'").arg(id);
       QSqlQuery query;
       query.exec(sql);
}
 
  
void MainWindow::on_pushButton_5_clicked()
{
        QSqlQuery q;
        q.exec("select *from ChannelValues1");
        while(q.next())   //遍历完为false
        {
            //以下标
            //qDebug()< 
  
           // < 
  
            //以字段
            qDebug()< 
  
            < 
  
        }
}
 
  
void MainWindow::on_pushButton_6_clicked()
{
    QSqlQuery query;
    QString sql1 = "DROP table ChannelValues1";
    query.exec(sql1);
}
 
 

你可能感兴趣的:(数据库,qt,数据库,mysql)