Qt之QsqlQuery建立插入数据

学习目标:

QsqlQuery建立插入数据


代码:

QSqlDatabase database;
    database=QSqlDatabase::addDatabase("QMYSQL","first");//第二个参数 在需要连接多个数据库的时候 需要指定连接名,可随意取名
    database.setHostName("127.0.0.1");
    database.setPort(3306);
    database.setUserName("root");
    database.setPassword("123456");
    database.setDatabaseName("st");//连接st这个数据库
    if(!database.open())
    {
          
   
        qDebug()<<"fail to connect mysql"<<database.lastError().text();

    }
    else {
          
   
        qDebug()<<"open sucess";
    }
    
    QSqlQuery query(database);
    query.exec("create table student(id int primary Key , name varchar(255), age int ,score int);");
    
//    //插入
//    query.exec("insert into student(id, name, age,score) values(1, Mike, 18, 59);");
    
    //批量插入 //odbc风格
    // ?相当于占位符
    query.prepare("insert into student(id, name, age,score) values(?, ?, ?, ?);");
    //给字段设置内容 list
    //给字段设置相应的值
    QVariantList idList;
    idList<<101<<102<<103<<104;
    QVariantList nameList;
    nameList<<"xiaoming"<<"xiaozheng"<<"xiaoli"<<"lihua";
    QVariantList ageList;
    ageList<<18<<19<<20<<21;
    QVariantList scoreList;
    scoreList<<60<<61<<62<<63;
    
    //给字段把那个定相应的值 按顺序绑定
    
    query.addBindValue(idList);
    query.addBindValue(nameList);
    query.addBindValue(ageList);
    query.addBindValue(scoreList);
    //执行预处理命令
    query.execBatch();
    
   
    
    /*-------------------------------------------------------*/
    /*
    //Oracle风格
    //占位符为 :+自定义名字
    query.prepare("insert into student(id, name, age,score) values(:id, :name, :age, :score);");

    //给字段设置内容 list
    //给字段设置相应的值
    QVariantList idList;
    idList<<101<<102<<103<<104;
    QVariantList nameList;
    nameList<<"xiaoming"<<"xiaozheng"<<"xiaoli"<<"lihua";
    QVariantList ageList;
    ageList<<18<<19<<20<<21;
    QVariantList scoreList;
    scoreList<<60<<61<<62<<63;
    
    query.bindValue(":id",idList);
    query.bindValue(":name",nameList);
    query.bindValue(":age",ageList);
    query.bindValue(":score",scoreList);
    
    query.execBatch();
    
    
 */
经验分享 程序员 微信小程序 职场和发展