Qt 连接SQL Server服务器,上传MES数据

用户数据库设置对话框,点击【OK】保存参数
Qt 连接SQL Server服务器,上传MES数据_第1张图片

void MySQLDialog::on_pbnOK_clicked()
{
    m_isVerify = ui->cbxVerify->isChecked();
    QString ip = ui->ledIP->text();
    QString database = ui->ledDatabase->text();
    QString userName = ui->ledUserName->text();
    QString password = ui->ledPassword->text();
    QString tester = ui->ledOperator->text();

    if(ip.isEmpty()){
        QMessageBox::warning(this, "ERROR", tr("输入服务器IP不能为空"), QMessageBox::Ok);
    }
    else if(database.isEmpty()){
        QMessageBox::warning(this, "ERROR", tr("输入数据库不能为空"), QMessageBox::Ok);
    }
    else if(userName.isEmpty()){
        QMessageBox::warning(this, "ERROR", tr("输入用户名不能为空"), QMessageBox::Ok);
    }
    else if(password.isEmpty()){
        QMessageBox::warning(this, "ERROR", tr("输入密码不能为空"), QMessageBox::Ok);
    }
    else if(tester.isEmpty()){
        QMessageBox::warning(this, "ERROR", tr("输入操作员编号不能为空"), QMessageBox::Ok);
    }
    else{
        QSettings setting("mes.ini", QSettings::IniFormat);
        setting.beginGroup("SQLSERVER");
        setting.setValue("isVerify", m_isVerify);
        setting.setValue("Server", ip);
        setting.setValue("Database", database);
        setting.setValue("UserName", userName);
        setting.setValue("Password", password);
        setting.setValue("Operator", tester);
        setting.endGroup();
        this->accept();
    }
}

点击【取消】,重新加载原来设置参数。

void MySQLDialog::on_pbnCancel_clicked()
{
    loadIniFile();
    this->reject();
}
void MySQLDialog::loadIniFile()
{
    QSettings setting("mes.ini", QSettings::IniFormat);
    setting.beginGroup("SQLSERVER");
    m_isVerify = setting.value("isVerify", false).toBool();
    QString ip = setting.value("Server", "192.168.0.1").toString();
    QString database = setting.value("Database", "Database").toString();
    QString userName = setting.value("UserName", "root").toString();
    QString password = setting.value("Password", "123456").toString();
    QString tester = setting.value("Operator", "TGD002").toString();
    setting.endGroup();

    ui->cbxVerify->setChecked(m_isVerify);
    ui->ledIP->setText(ip);
    ui->ledUserName->setText(userName);
    ui->ledDatabase->setText(database);
    ui->ledPassword->setText(password);
    ui->ledOperator->setText(tester);
}

主程序运行时,读取ini文件数据。如果设置上传数据,则连接数据库服务器。

getSqlServerAttributes();
if(sqlData.isVerify)
     initBLWDatabase();

sqlData是一个自定义的结构体,保存SQLSERVER参数

void MySQLServer::getSqlServerAttributes()
{
    QSettings setting("mes.ini", QSettings::IniFormat);
    setting.beginGroup("SQLSERVER");
    sqlData.isVerify = setting.value("isVerify", false).toBool();
    sqlData.server = setting.value("Server", "192.168.0.1").toString();
    sqlData.database = setting.value("Database", "Database").toString();
    sqlData.userName = setting.value("UserName", "root").toString();
    sqlData.Password = setting.value("Password", "123456").toString();
    sqlData.Operator = setting.value("Operator", "TGD002").toString();
    setting.endGroup();
}

连接服务器,创建表格。

void MySQLServer::initBLWDatabase()
{
    blw_db = QSqlDatabase::addDatabase("QODBC", "blwConnect");
    if(!blw_db.isValid())
    {
        QMessageBox::warning(this, "ERROR", tr("QODBC hasn't a valid driver, %1").arg(blw_db.lastError().databaseText()), QMessageBox::Ok);
        return;
    }
    QSettings setting("mes.ini", QSettings::IniFormat);
    QString sqlStr = QString("Server=%1;Database=%2;UID=%3;PWD=%4;")
            .arg(setting.value("SQLSERVER/Server", "").toString())
            .arg(setting.value("SQLSERVER/Database", "").toString())
            .arg(setting.value("SQLSERVER/UserName", "").toString())
            .arg(setting.value("SQLSERVER/Password", "").toString());
    QString dsn = QString("Driver={SQL Server};%1Trusted_Connection=no").arg(sqlStr);
    blw_db.setDatabaseName(dsn);
    if(blw_db.open())
        createBLWTable();
    else{
        QMessageBox::critical(this, "Error", tr("Open Database Fail : %1").arg(blw_db.lastError().databaseText()), QMessageBox::Ok);
    }
}

创建表格函数

void MySQLServer::createBLWTable()
{
    if(!(blw_db.tables().contains("blw_data"))){
        QSqlQuery query(blw_db);
        QString cmd = QString("CREATE TABLE blw_data ( "
                             "ID                                    int identity(1,1) primary key not null,"
                             "Barcode                               VARCHAR (50),"
                             "Datetime                              DATETIME,"
                             "Operator                              VARCHAR (30),"
                             "Result                                VARCHAR (5),"
                             "NoloadVoltage                        Float,"
                             "ACResistance                         Float,"
                             "OverChargeProtectCurrent             Float,"
                             "ChargeCurrent                        Float,"
                             "ChargeVoltage                        Float,"
                             "DischargeOvercurrentProtectCurrent   VARCHAR (20),"
                             "DischargeCurrent                     Float,"
                             "DischargeVoltage                     Float,"
                             "ShortProtectTime                     Float,"
                             "EndVoltage                           Float,"
                             "DischargeOvercurrentProtectTime      Float,"
                             "MatchedResistance1                   Float,"
                             "MatchedResistance2                   Float,"
                             "ChargeDCResistance                   Float,"
                             "DischargeDCResistance                Float,"
                             "ChargeOvercurrentProtectTime         Float,"
                             "ChargeOvercurrentRecoveryTime        Float,"
                             "DischargeOvercurrentRecoveryTime     Float,"
                             "SecDischargeOvercurrentProtectCurrent Float,"
                             "SecDischargeOvercurrentProtectTime    Float,"
                             "SecDischargeOvercurrentRecoveryTime   Float,"
                             "BCResistance                          Float "
                             " );");
        if(!query.exec(cmd)){
            QMessageBox::critical(this, "ERROR", tr("Create Table 'blw_data' Fail. %1").arg(blw_db.lastError().databaseText()), QMessageBox::Ok);
        }else{
            qDebug() << "create table success";
        }
    }
}

其中创建表格的时候遇到一个问题,开始是使用DOUBLE类型的,语句执行失败。查资料发现SQL Server不支持double数据类型,改为float之后执行成功。

主键ID自增语句也是,建数据表使用工具PowerDesigner,语句是auto_increment。也是语句执行失败,后面改为int identity(1,1) primary key not null
Qt 连接SQL Server服务器,上传MES数据_第2张图片
数据插入函数

QSqlQuery query(blw_db);
QString cmd = QString("INSERT INTO blw_data (%1) VALUES (%2);").arg(field).arg(value);
if(blw_db.isOpen()){
    if(!query.exec(cmd)){
        ui->lblMessage->setStyleSheet("background-color: rgb(255, 0, 0);");
        ui->lblMessage->setText(tr("测试数据上传失败, %1").arg(query.lastError().text()));
    }else{
        ui->lblMessage->setStyleSheet("background-color: rgb(0, 255, 0);");
        ui->lblMessage->setText(tr("测试数据上传成功"));
    }
}else{
    QMessageBox::critical(this, "Save ERROR", tr("数据库没有打开,请重启软件. The database is not open."), QMessageBox::Ok);
}

你可能感兴趣的:(Qt)