2009-12-03 75 views
0

下面的代碼工作完美:SQLite ADO .NET - 如何正確使用查詢生成器?

var oDb = new SQLiteConnection(); 
    oDb.ConnectionString = String.Format(
     "Data Source={0};" 
    + "Synchronous=Full;", 
    "test.db"); 
    oDb.Open(); 
    SQLiteCommand oCmd = new SQLiteCommand(oDb); 
    oCmd.CommandText = "create table tests ("; 
    oCmd.CommandText += " id guid primary key not null"; 
    oCmd.CommandText += ", name text default 'none')"; 
    oCmd.ExecuteNonQuery(); 

但如果我嘗試使用查詢構建器(自動逃跑字符串):

var oDb = new SQLiteConnection(); 
    oDb.ConnectionString = String.Format(
     "Data Source={0};" 
    + "Synchronous=Full;", 
    "test.db"); 
    oDb.Open(); 
    SQLiteCommand oCmd = new SQLiteCommand(oDb); 
    oCmd.CommandText = "create table tests ("; 
    oCmd.CommandText += " id guid primary key not null"; 
    oCmd.CommandText += ", name text default @param)"; 
    var oParam = new SQLiteParameter("@param", "none"); 
    oCmd.Parameters.Add(oParam); 
    oCmd.ExecuteNonQuery(); 

引發異常:

SQLite error 
near "@param": syntax error 

燦任何人請留出一點知識,並提示我我做錯了什麼?

回答

2

雖然我沒有測試過我,這應該工作: oCmd.Parameters.AddWithValue("@param", "none"); 編輯:

EDIT2:如果添加()圍繞@param它的工作原理好,爲ExecuteNonQuery()不工作,但結果不是預期的結果。 @param不會被替換爲acutal參數。 請勿使用此代碼! (現在是一個社區的wiki。也許有人能解決這個問題?)

SQLiteCommand oCmd = new SQLiteCommand(oDb); 
oCmd.CommandText = "create table tests ("; 
oCmd.CommandText += " id guid primary key not null"; 
oCmd.CommandText += ", name text default (@param))"; 
var oParam = new SQLiteParameter("@param", "none"); 
oCmd.Parameters.Add(oParam); 
oCmd.ExecuteNonQuery(); 
+0

完全相同例外:( – grigoryvp 2009-12-03 20:41:00

+0

我改變了我的答案的一個工作版本,但我真的不知道爲什麼那些()必須是目前:http://www.sqlite.org/syntaxdiagrams.html#column-constraint指出,也可以有一個沒有括號的文字... – tobsen 2009-12-03 22:28:16

+1

我很驚訝它可以工作,我不知道你可以使用參數綁定的數據定義語言語句 – tuinstoel 2009-12-04 06:54:13