QSqlQuery 插入大量数据、碰到插入失败的跳过、继续插入

void Widget::on_pushButton_2_clicked()
{
    int number = 0;

    //开启事务
    if(db.transaction())
    {
        qDebug()<<"open ok";
    }
    else{
        qDebug()<<"open error";
    }

    QSqlQuery qq(db); //以下执行相关QSL语句
    qq.prepare("select * from net_clear_ent_info");
    qq.exec();
    int j = 0;
    while(qq.next())
    {
        qDebug()<<"数量: "<<j;
        j++;
        //获取手机号
        QString phone = qq.value(2).toString();
        if(phone.contains(","))
        {
            QStringList li_phone = phone.split(",");

            for(int j=0; j < li_phone.length(); j++)
            {
                number++;
                QString many_phone = li_phone[j].replace("-","");

                QString str ="insert into phone_net_clear_ent_info (name,phone,address) values ('"+qq.value(1).toString()+"', '"+many_phone+"', '"+qq.value(3).toString()+"')";
                QSqlQuery query;
                query.exec(str);
            }

        }
        else
        {
            number++;
            QString clear_phone = phone.replace("-","");

            QString str1 ="insert into phone_net_clear_ent_info (name,phone,address) values ('"+qq.value(1).toString()+"', '"+clear_phone+"', '"+qq.value(3).toString()+"')";
            QSqlQuery query;
            query.exec(str1);
        }

        //提交事务
        if(db.commit())
        {
            qDebug()<<"commit ok";
        }
        else
            qDebug()<<"commit error";
            //失败以后可以进行回滚

    }


    qDebug()<<"一共这么多号码:"<<number;

}

posted on 2021-09-16 15:42  袁佳佳  阅读(622)  评论(0编辑  收藏  举报

导航