QSqlQuery :: prepare:数据库未打开

时间:2012-01-31 11:12:10

标签: c++ mysql qt

我正在尝试使用DB MySql进行SELECT。这是代码:

qDebug() << "status" << db.db().isOpen();
query.prepare("SELECT jobId FROM jobs");

结果是:

status true 
QSqlQuery::prepare: database not open

我该如何解决?

3 个答案:

答案 0 :(得分:4)

尝试在QSqlQuery的构造函数中传递数据库:

QSqlQuery query(db.db());
query.prepare("SELECT jobId FROM jobs");

答案 1 :(得分:0)

QSqlQuery (
    const QString & query = QString(),
    QSqlDatabase db = QSqlDatabase()
)
QSqlDatabase QSqlDatabase::database (
    const QString & connectionName = QLatin1String(defaultConnection),
    bool open = true
) [static]

QSqlQuery query(
    QString("SELECT jobId FROM jobs"),
    QSqlDatabase::database("you name connection")
);
query.exec();

答案 2 :(得分:0)

这是我最近写的一段摘录

//Add the database connection
QSqlDatabase m_db = QSqlDatabase::addDatabase("MYSQL", "m_db_connect");
//Set relevant settings
m_db.setHostName("127.0.0.1");
m_db.setDatabaseName("maindb");
m_db.setUserName("neox");
m_db.setPassword("12345567");
//Open the database
if(!m_db.open()) {
    qWarning() << __FUNCTION__ << "Failed to open main database; aborting...";
    qWarning() << __FUNCTION__ << m_db.lastError().text();
    return false;
}
//Create query string
QString queryString("SELECT id from events");
QSqlQuery query(m_db, queryString);   
//Check if the query has executed properly
if(!query.exec()) {
    qWarning() << __FUNCTION__ <<":"<<__LINE__<<"Failed to fetch ids";
    qWarning() << __FUNCTION__ <<":"<<__LINE__<<m_db.lastError().text();
    return false;
}
QList<int> id_list;
//Here I check whether the select has returned any results and append them to the list
while(query.next()) {
    int id = query.value(0).toInt();
    id_list.append(id);
}

到目前为止,这对我有用,我希望这是有帮助的