2016-11-04 52 views
2

在SQLite網站上,C#中的SQLite缺少與VS2015中的「SQLite for Universal Windows Platform」擴展相關的文檔。 有沒有人見過這個擴展特定的文檔?UWP - 檢查表是否存在

我想看看我的數據庫中是否存在一個表,但找不到一個方法來做到這一點。 這是我在做什麼,爲什麼:

SQLite.Net.SQLiteConnection conn; 

string path = path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "entries.sqlite"); 
if (!System.IO.File.Exists(path)) 
{ 
    conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); 
    conn.CreateTable<Entry>(); 
} 
else 
{ 
    conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); 
} 

我這樣做,這是執行時,因爲:如果它不存在

conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); 

的文件被創建。所以首先我需要測試它是否存在。我的假設是,如果文件存在,我的表就會存在,因爲沒有創建文件後沒有創建表的情況。 我在所提供的方法範圍內是否缺少一些更直接的表測試方法?

謝謝!

PS。我檢查了我的問題是否已被回答,但沒有找到與此API直接相關的任何內容。

回答

0

您可以使用系統sqlite_master表的查詢,看是否與給定名稱的表存在:

var tableQuery = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='Entry';" 
bool tableExists = conn.ExecuteScalar<int>(tableQuery) == 1; 

如果該表不存在,查詢將返回0,如果存在的話,它將返回1.

但是,即使表已存在,您也不必擔心調用conn.CreateTable<Entry>();。 SQLite.net足夠聰明,只有當它還不存在時才能創建表。如果該表已經在數據庫中,則該調用將被忽略。

+0

感謝這個!您是否也碰巧有鏈接到文檔?我還沒有找到全面的。 – VegasVed

+0

此查詢應該在SQLite.org上的SQLite文檔中記錄(它不是UWP特定的)。但是,對於SQLite.Net上的文檔,您可能只剩下相關的文章以及項目的Github頁面上提供的內容:-) –

0

通用的解決方案:

public bool TableIsExists<T>(SQLiteConnection conn) 
{ 
    var q = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"; 
    var cmd = conn.CreateCommand(q, typeof(T).Name); 
    return cmd.ExecuteScalar<string>() != null; 
}