Qt 使用sqlserver

1. pro 添加

 QT       +=sql

2. 

void MainWindow::connectSqlServer()
{



    QSettings *setIni = new QSettings("config.ini", QSettings::IniFormat);
    setIni->beginGroup("DatabaseServer");
    QString serverIp=setIni->value("ServerIP").toString();
    QString databaseName=setIni->value("DatabaseName").toString();
    QString user=setIni->value("User").toString();
    QString password=setIni->value("Password").toString();
    setIni->endGroup();
    delete setIni;


    if(serverIp==""||databaseName==""||user==""||password=="")
    {
        statusLabel->setText("服務器設置錯誤,請到服務器設置重新設置");
        statusLabel->setStyleSheet("color:red;");
        return;

    }

    //QSqlDatabase db1 = QSqlDatabase::addDatabase("QODBC");
     db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName(QString("DRIVER={SQL SERVER};"
                                 "SERVER=%1;"
                                 "DATABASE=%2;"
                                  "UID=%3;"
                                  "PWD=%4;").arg(serverIp)
                                            .arg(databaseName)
                                            .arg(user)
                                            .arg(password));

      if (db.open())
      {

          //qDebug()<<"Connect to Database Success!";
          statusLabel->setText("服務器連接正常");
          statusLabel->setStyleSheet("color: rgb(0, 0, 0);");

      }
      else
      {

           qDebug()<<"++++++++++++db error+++++++++++++"<<db.lastError().databaseText();
           statusLabel->setText("服務器連接錯誤,請到服務器設置重新設置");
           statusLabel->setStyleSheet("color:red;");

      }






}

 

void MainWindow::insertDB(QStringList lst)
{
   QSqlQuery query=QSqlQuery(db);

   QString num=lst.at(5).trimmed();
   num.replace("kg","").replace("g","").replace("lb","").replace("tl","");

   QString sql="INSERT INTO sny_file(sny01,sny02,sny03,sny04,sny05,sny06,sny07,sny08,sny09,sny10)";
   sql=sql+" VALUES(";
   sql=sql+"'"+lst.at(0).trimmed()+"','"+lst.at(2).trimmed()+"','"+lst.at(3).trimmed()+"','"+lst.at(4).trimmed()+"',";
   sql=sql+"'"+num+"','"+lst.at(6).trimmed()+"','"+lst.at(7).trimmed()+"','"+lst.at(8).trimmed()+"',";
   sql=sql+"'"+lst.at(1)+"','N')";

   qDebug()<<sql;
   query.exec(sql);


}

 

posted @ 2015-12-19 10:48  ike_li  阅读(2187)  评论(0编辑  收藏  举报