簡體   English   中英

QT噩夢與2個同時數據庫連接

[英]QT nightmare with 2 simultaneous database connections

我需要在我的QT代碼中同時讀取Microsoft ODBC數據庫和Postgres數據庫。

問題

  1. 打開數據庫連接后,如何指示qsqlQuery使用哪個連接?
  2. 為什么我的數據庫連接失敗但這些數據庫存在
謝謝

 #include <QtCore/QCoreApplication> #include <QSqlDatabase> #include <QSqlQuery> #include <Qdebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //odbc QSqlDatabase dbODBC= QSqlDatabase::addDatabase("QODBC","microsoft_connection"); dbODBC.setDatabaseName("BIO"); if(!dbODBC.open()) { qDebug()<<"failed to open BIO"; exit(1); } //postgress QSqlDatabase dbPostgres= QSqlDatabase::addDatabase("QPSQL","postgres_connection"); dbPostgres.setDatabaseName("makerere_boys_db"); dbPostgres.setHostName("127.0.0.1"); dbPostgres.setUserName("postgres"); dbPostgres.setPassword("student"); if (!dbPostgres.open()) { qDebug()<<"failed to open postgres database"; exit(1); } //how do i tell QSqlQuery to use dbODBC instead of dbPostgress?. Frustration follows QSqlQuery query; query.exec("SELECT * FROM fees"); qDebug()<<query.value(0).toString(); return a.exec(); system("pause"); } 

上面的代碼可以編譯,但是QSqlQuery表示數據庫未打開

請注意,您正在將此 ctor用於查詢對象,並且僅對兩個參數都使用了默認參數。 注意文檔的內容。 因此,您要告訴ctor使用默認數據庫,該數據庫必須是適合您的postgres數據庫。

對於問題1:您需要將數據庫作為參數傳遞給QSqlQuery構造函數:

QSqlQuery query(dbPostgres);
...

對於問題2:查看QSqlDatabase類的文檔。 addDatabase的功能描述的底部,它指出:

在使用連接之前,必須將其初始化。 例如,調用部分或全部setDatabaseName(),setUserName(),setPassword(),setHostName(),setPort()和setConnectOptions(),最后調用open()。

看起來您只在調用setDatabaseName。 您可能需要為對象提供所描述的其他信息。

QSqlQuery query1(QSqlDatabase::database("postgres_connection"));
query1.exec("SELECT * FROM fees");
while (query1.next()){
    QString col0 = query1.value(0).toString();
    QString col1 = query1.value(1).toString();
    qDebug() <<  QString("%1 , %2").arg(col0).arg(col1);
}



QSqlQuery query2(QSqlDatabase::database("microsoft_connection"));
query2.exec("SELECT * FROM fees");    
while (query2.next()){
    QString col0 = query2.value(0).toString();
    QString col1 = query2.value(1).toString();
    qDebug() <<  QString("%1 , %2").arg(col0).arg(col1);
}

有點離題,但是您實際上不需要實例化QCoreApplication (或QApplication )來對RDBMS運行查詢。 您可以放心評論

// this line
#include <QtCore/QCoreApplication>
// and this line
QCoreApplication a(argc, argv);
// and this line
return a.exec();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM