1. 程式人生 > >QT 關於Driver not loaded 與 結構體的建構函式

QT 關於Driver not loaded 與 結構體的建構函式

QT 關於Driver not loaded

在程式中使用SQLite資料庫,如下的程式碼:

    QSqlDatabase db;
    QSqlQuery query;
    db = QSqlDatabase::addDatabase("QSQLITE");
      if(db.open()){
        if(!query.exec("create table student(name text)")){
            qDebug()<<query.lastError();
        }
        db.close
(); }

總是報錯:Driver not loaded Driver not loaded.
在幫助文件中,檢視說明,有這樣的話:

Ensure that you are using a shared Qt library; you cannot use the plugins with a static build.
Ensure that the plugin is in the correct directory. You can use QApplication::libraryPaths() to determine where Qt looks for plugins.
Ensure that
the client libraries of the DBMS are available on the system. On Unix, run the command ldd and pass the name of the plugin as parameter, for example ldd libqsqlmysql.so. You will get a warning if any of the client libraries couldn't be found. On Windows, you can use Visual Studio's dependency walker. With Qt Creator, you can update the
PATH environment variable in the Run section of the Project panel to include the path to the folder containing the client libraries. Compile Qt with QT_DEBUG_COMPONENT defined to get very verbose debug output when loading plugins.

奇怪,我檢視QApplication::libraryPaths()輸出的資訊,確信plugin路徑正確。動態庫檔案也存在:/Users/weiyang/Qt5.9.2/5.9.2/clang_64/plugins/sqldrivers。仔細檢視輸出,我觀察到在此之前還有QSqlQuery::exec: database not open
我試著這樣改:

    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QSQLITE");
    QSqlQuery query;

先建立好Sqlite connection class,然後建立query物件。OK!

結構體建構函式

假設結構體中包含有參建構函式,如下:

typedef struct _Data {
    int a;
    string s;
    _Data(int _a, string _s){ a = _a; s = _s; }
}Data;

那麼,就不能使用類似於這樣的語句:sentenceUnit senUnit
C++會嘗試匹配move constructure, copy constructrue, 有參建構函式。

    Data d(1,"hello");
    Data d1(d);             //copy constructrue
    Data d2(std::move(d));  //move constructure.

如果這些都沒有,那麼編譯器則會報出不匹配的錯誤。
我們需要自己寫出無參建構函式。
那麼如果是類的話,情況是類似的:

class Data {
public:
    int a;
    string s;
    Data(int _a, string _s){ a = _a; s = _s; }
};

int main()
{
    Data d = Data(1,"hello"); //we can't use 'Data d()', or compiler regard it as a functon.
    Data d1(d);             //copy constructrue
    Data d2(std::move(d));  //move constructure.
    Data d3;                //error: no matching constructure.
    return 0;
}