简体   繁体   中英

Parameterized query with parameter in select returns invalid data

I have the following code:

string connectionString = 
    "Provider=Microsoft.JET.OLEDB.4.0;" + 
    "data source=" + processProgramPath + ";";

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    connection.Open();
    using (OleDbCommand command = new OleDbCommand(
        "SELECT @Value " +
        "FROM BONDPARAMETERS " +
        "WHERE BONDPARAMETERS.SetName = @SetName", connection))
    {
        command.Parameters.AddWithValue("@Value", value);
        command.Parameters.AddWithValue("@SetName", setName);               

        var result = command.ExecuteScalar();
        return result.ToString();
    }
}

What I am expecting to get is 760 as a result. However I am getting the title for the column which is StartForce.

value = "StartForce" setName = "450(18)-F-OE"

If I change the using to this:

using (OleDbCommand command = new OleDbCommand("SELECT "+value+" " +

it works. What gives?

Thanks in advance

You can't build SQL dynamically with parameters like that. See this question: Using C# SQL Parameterization on Column Names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM