我试图尽可能地参数化一些SQL语句,但在某些情况下,我需要包含一些在代码中其他地方生成的原始SQL文本。
在一个案例中,我试图替换看起来像这样的代码:
using (SQLiteCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandTimeout = 0;
cmd.CommandText = String.Format("CREATE VIEW {0} AS {1}", viewName, sqlQuery);
cmd.ExecuteNonQuery();
}
看起来像这样:
using (SQLiteCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandTimeout = 0;
cmd.CommandText = "CREATE VIEW [@view] AS @sql";
cmd.Parameters.AddWithValue("@view", viewName);
cmd.Parameters.AddWithValue("@sql", sqlQuery);
cmd.ExecuteNonQuery();
}
但是,这会产生以下错误:
System.Data.SQLite.SQLiteException (0x80004005): SQL logic error or missing database
near "@sql": syntax error
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
另一方面,以下代码不会生成错误:
using (SQLiteCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandTimeout = 0;
cmd.CommandText = String.Format("CREATE VIEW [@view] AS {0}", sqlQuery);
cmd.Parameters.AddWithValue("@view", viewName);
cmd.ExecuteNonQuery();
}
我的语法有问题,还是不可能在那里使用参数?我认为它可能是后者,因为它应该是另一个参数化查询,但我的搜索没有提出任何人试图将SELECT语句放入参数的例子。