qt数据库sql语句使用c++中的变量

void SerialWidget::on_btnMysql_clicked()
{
    qDebug()<<QSqlDatabase::drivers()<<endl; /*列出qt可用的数据库*/
    //链接mysql数据库
    QSqlDatabase db( QSqlDatabase::addDatabase( "QMYSQL" ) );
    db.setHostName("localhost");
    db.setDatabaseName("test");
    db.setUserName("root");
    db.setPassword("344555");
    if(!db.open())
    {
        QMessageBox::critical(0, QObject::tr("Databse Error"), db.lastError().text());
        qDebug()<<db.lastError()<<endl;
    }
    else
    {
        qDebug()<<"Ok"<<endl;
    }

    /************************/
    QSqlQuery query;
    bool ret1 = query.exec("create table home(temperature varchar(10) not null primary key,humidity varchar(10) not null);");
    QString sql_insert = QString("insert into home values('%1','%2')").arg(temperature).arg(humidity);
    bool ret2 = query.exec(sql_insert);
    bool ret3 = query.exec("select * from home");

    qDebug()<< ret1 << ret2 << ret3;
    qDebug()<<"temperature     humidity";
    while(query.next())
    {
        qDebug()<<query.value(0).toString()<<"   "<<query.value(1).toString();
    }
    /***************************/

}

  

posted @ 2015-11-27 19:48  CrazyDiode  阅读(1206)  评论(0编辑  收藏  举报