有求必应

导航

qt查询mysql数据库读不到数据

查了很多方法,也没找到原因,把以前写过的放进来就好了,我开始也是这么写的  ,只不过没加isok做判断,没有进一步测试,希望对你们有帮助。

QSqlQuery MysqlSingleton::select(QString sql)
{
    QSqlQuery query(dbconn);

    mutex.lock();
    bool isok = query.exec(sql);
    mutex.unlock();

    if(!isok)
    {
        cout << QString("查询失败!%1").arg(query.lastError().text());
    }
    else
    {
        cout << "start select";
/*这一块放到读取数据的地方
while(query.next()) { QString id = query.value(0).toString(); QString name = query.value(1).toString(); QString age = query.value(2).toString(); cout <<"id:" <<id<<" name:" <<name<<" age:" <<age; }
*/ }
return query; }

顺便存一下增删改

void MysqlSingleton::operateDB(QString sql)
{
    QSqlQuery query(dbconn);

    mutex.lock();
    if(!query.exec(sql))
    {
        qDebug() << "Error: Fail to insert ." << query.lastError();
    }
    mutex.unlock();



}
void MysqlSingleton::insertSQL(QString sql){    operateDB(sql); cout << "insert OK";}
void MysqlSingleton::deleteSQL(QString sql){    operateDB(sql); cout << "delete OK";}
void MysqlSingleton::updateSQL(QString sql){    operateDB(sql); cout << "update OK";}

sql语句我就不写了,网上有很多。

那顺便把数据库创建和表的创建也放进来吧,省的以后自己找

void MysqlSingleton::createDB()
{
    QString querystring;
    //创建数据库
    dbconn = QSqlDatabase::database(DB_NAME);
    querystring = "CREATE DATABASE IF NOT EXISTS " + DB_NAME;

    dbconn.exec(querystring);
    if (dbconn.lastError().isValid())
    {
        cout<<"Create database failed."<<dbconn.lastError();
        return;
    }
}

/*
"CREATE TABLE IF NOT EXISTS first"
                    "("
                    "id int auto_increment primary key ,"  //自增主键
                    "Name varchar(20),"
                    "age int"
                    ")"
*/

void MysqlSingleton::createTable(QString sql)
{
    //创建数据表student
    dbconn.setDatabaseName(DB_NAME);
    if(!dbconn.open())
    {
        cout<<"database open failed";
        return;
    }
    
    dbconn.exec(sql);//执行创建数据表语句
    if (dbconn.lastError().isValid())
    {
        cout<<"Student table creat failed:" << dbconn.lastError();
        return;
    }

    if (QSqlDatabase::database().driver()->hasFeature(QSqlDriver::Transactions))
    {
        //检查是否支持事务
        cout<<"DB shiwu OK";
//        QSqlDatabase::database().transaction();
//        QSqlQuery query;
//        query.exec("SELECT id FROM T_STUDENT WHERE class=1");
//        if (query.next())
//        {
//            query.exec("INSERT INTO T_STUDENT (id,name,age) VALUES (3,'小李',13)");
//        }
//        QSqlDatabase::database().commit();
    }

    //支持中文
    dbconn.exec("alter table first convert to character set utf8");
}

 

posted on 2019-11-13 13:38  名侦探江户川  阅读(1599)  评论(0编辑  收藏  举报