开发者

error with SqlCe Parameters

I have made MANY parameterised queries in my time on this lovely planet, and none have thrown an error like this... WTFudge?!?!

ERROR:

There was an error parsing the query. [
Token line number = 1,
Token line offset = 20,
Token in error = @table ]
开发者_JS百科

Obviously the compiler doesn't like my SQL statement... but I see no problem???

Here is my code.

using (SqlCeConnection con = new SqlCeConnection(_connection))
{
    string sqlString = "SELECT @colID FROM @table WHERE @keyCol = @key";

    SqlCeCommand cmd = new SqlCeCommand(sqlString, con);
    cmd.Parameters.Add(new SqlCeParameter("@table", tableName));
    cmd.Parameters.Add(new SqlCeParameter("@colID", columnIdName));
    cmd.Parameters.Add(new SqlCeParameter("@keyCol", keyColumnName));
    cmd.Parameters.Add(new SqlCeParameter("@key", key));

    try
    {
        con.Open();
        return cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.Write(ex.Message);
        throw new System.InvalidOperationException("Invalid Read. Are You Sure The Record Exists", ex);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
            con.Close();
        cmd.Dispose();
        GC.Collect();
    }
}

as you can see its a VERY simple SQL statement. I though "@table" may have been stupidly reserved or something... so ive tried @tableName, @var, @everything!!! dont know what the problem is.

During debug I checked that there was actually a @table parameter in the SqlCeParameterCollection And it was there. Clear as day!!

error with SqlCe Parameters


Since you are in C# (as opposed to stored procs)

string sqlString = "SELECT " + columnIdName + 
" FROM " +tableName "WHERE " + keyColumnName + "= @key";

You will want to verify that columnIdName, tableName, keyColumnName are all restricted to a list of values (or at the very least, restrict the length to, say 50 characters), otherwise this procedure is optimized for insecurity and sql injection attacks.


This affected me too on SqlCe. But in Sql Server and in SqlExpress you can use a paarameter for table name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜