2009-12-03 71 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