System.Data.SQLite parameterized queries with multiple values?

柔情痞子 提交于 2019-12-21 03:39:09

问题


I am trying to do run a bulk deletion using parameterized queries. Currently, I have the following code:

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);

foreach (string name in selected)
    pendingDeletions.Parameters.AddWithValue("$name", name);

pendingDeletions.ExecuteNonQuery();

However, the value of the parameter seems to be overwritten each time and I end up just removing the last centre. What is the correct way to execute a parameterized query with a list of values?


回答1:


foreach (string name in selected) 
{
    pendingDeletions.Parameters.AddWithValue("$name", name);  <--
    pendingDeletions.ExecuteNonQuery(); 
}



回答2:


Rezzie, your current code is equivalent to:

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);


foreach (string name in selected)
{
    pendingDeletions.Parameters.AddWithValue("$name", centre.Name);
}

pendingDeletions.ExecuteNonQuery();

Which means you are only executing the query once, with the last value in your 'selected' enumerable.

This is the prime reason that I ALWAYS ALWAYS ALWAYS use block delimiters on conditionals and loops ALWAYS.

So, if you enclose the parameter assignment and the query execution in the loop you should be good to go.

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);


foreach (string name in selected)
{
    pendingDeletions.Parameters.AddWithValue("$name", centre.Name);
    pendingDeletions.ExecuteNonQuery();
}



回答3:


I took this example from http://rosettacode.org/wiki/Parametrized_SQL_statement b/c the syntax here (with the '$' didn't work for me)

SqlConnection tConn = new SqlConnection("ConnectionString");

SqlCommand tCommand = new SqlCommand();
tCommand.Connection = tConn;
tCommand.CommandText = "UPDATE players SET name = @name, score = @score, active = @active WHERE jerseyNum = @jerseyNum";

tCommand.Parameters.Add(new SqlParameter("@name", System.Data.SqlDbType.VarChar).Value = "Smith, Steve");
tCommand.Parameters.Add(new SqlParameter("@score", System.Data.SqlDbType.Int).Value = "42");
tCommand.Parameters.Add(new SqlParameter("@active", System.Data.SqlDbType.Bit).Value = true);
tCommand.Parameters.Add(new SqlParameter("@jerseyNum", System.Data.SqlDbType.Int).Value = "99");

tCommand.ExecuteNonQuery();


来源:https://stackoverflow.com/questions/2662999/system-data-sqlite-parameterized-queries-with-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!