2013-01-10 44 views
0

我想從Delphi中查詢SQLite 3表中的一個。 (我的數據庫是世界,我也有一張名爲City的表格)。我的代碼是:Delphi-sqlite查詢問題 - 表未找到

procedure TForm1.Button1Click(Sender: TObject); 
begin 
// Set the path of your database file. 
    // Replace "full_path_to_your_database_file" with the absolute path 
    // to your SQLite database file. 
    SQLConnection1.Params.Add('World.db3'); 
    try 
    // Establish the connection. 
    SQLConnection1.Connected := true; 
    Button1.Enabled := true; 
    Memo1.Text := 'Connection established!'; 
    except 
    on E: EDatabaseError do 
     ShowMessage('Exception raised with message' + E.Message); 
    end; 
end; 

procedure TForm1.ShowSelectResults(results: TDataSet); 
var 
    names: TStringList; 
    i: Integer; 
    currentField: TField; 
    currentLine: string; 
begin 
    if not results.IsEmpty then 
    begin 
    results.First; 
    names := TStringList.Create; 
    results.GetFieldNames(names); 
    while not results.Eof do 
    begin 
     currentLine := ''; 
     for i := 0 to names.Count - 1 do 
     begin 
     currentField := results.FieldByName(names[i]); 
     currentLine := currentLine + ' ' + currentField.AsString; 
     end; 
     memo1.Lines.Add(currentLine); 
     results.Next; 
    end; 
    end; 
end; 

procedure TForm1.Button2Click(Sender: TObject); 
var 
    results: TDataSet; 
    query: String; 
begin 
    Memo1.Clear; 
    // A random query 
    query := 'SELECT * FROM City;'; 

    try 
    // Execute the query on the database. 
    SQLConnection1.Execute(query, nil, results); 
    except 
    on E: Exception do 
     Memo1.Text := 'Exception raised with message: ' + E.Message; 
    end; 
    // Show the results of the query in a TMemo control. 
    ShowSelectResults(results); 
end; 

當我編譯並執行此代碼時,它正在連接到數據庫;但拋出這個錯誤。 「異常引發的消息:沒有這樣的表:城市」 我花了幾個小時來弄清楚爲什麼我打這個錯誤。試驗了這個代碼的很多版本。似乎也沒有工作。任何在這方面的幫助,高度讚賞。

回答

3

當SQLite找不到數據庫文件時,很高興創建並打開一個新文件。
您應該總是爲您的數據庫文件使用絕對路徑。

此外,你忘了,包括連接參數的參數名:

SQLConnection1.Params.Add('Database=' + ExtractFilePath(ParamStr(0)) + 'World.db3'); 
+0

我已經交叉檢查它。 World.db3保持在同一個目錄中。 – jimsweb

+2

是_「同一目錄」 _你在運行應用程序的_current directory_? – jachguate

+0

是「相同的目錄」和「當前目錄」是相同的。 :) – jimsweb