开发者

Using a ICollection Value in sqlite SELECT parameterized statment

开发者 https://www.devze.com 2022-12-31 01:01 出处:网络
Im trying to get all the entrys from a sqlite Database which have the same name as the keys in a Hashtable.

Im trying to get all the entrys from a sqlite Database which have the same name as the keys in a Hashtable.

My Statement 开发者_开发知识库looks like this.

// the keys from the hashtable are names equivalent 
// to name entrys in the SomeTable Names Collumn
Hashtable names;

String query = "SELECT Id, Name FROM SomeTable WHERE Name LIKE (@Names)";
SQLiteCommand command = new SQLiteCommand(query, _databaseConnection);
command.Parameters.AddWithValue("@Names", names.Keys);
SQLiteDataReader reader = reader.ExecuteReader();

while(reader.Read())
{
     Console.WriteLine("Name: {0}, ID: {1}", reader[1].ToString(), reader[0].ToString());
}

Im totally sure there are similar values in the Database, but i get nothing back and the reader does not execute. Is it impossible to add a ICollection as a Parameter Value so i need to start the reader only one time?


You don't want a LIKE clause in that select, you want an IN clause.

e.g. ultimately, you'd like to execute a query such as:

SELECT Id, Name FROM SomeTable WHERE Name IN ('case23', 'carson63000', 'fred')

Unfortunately, it seems that adding this in as a Parameter is not straightforward.

I found an older question, "Parameterizing a SQL IN clause?", which may provide some ideas.


SO to finish this up. Thanks to the link i got from Carlson63000 i got somthing working.

// First i build two String[] based on my Hastable.Keys. 
// One which holds the values, one which creates parameter names.

Hashtable hashNames;
String[] names = new String[hashName.Keys.Count];
String[] nameTags = new String[hashName.Keys.Count];
int c = 0;

foreach (String k in hashName.Keys)
{
     names[c] = k;
     nameTags[c] = "@tag" + c.ToString();
     c++;
}

// after this i create my statement using the nameTags String[]

String statementValueTags = String.Join(",", nameTags);
String query = String.Format("SELECT Name, FROM SomeTable WHERE (Name IN ({0}))", statementValueTags);

// for adding the parameterized Statements i use a for loop 
// where i add the values from my String[]
SQLiteCommand command = new SQLiteCommand(query, _databaseConnection);
for (int i = 0; i < names.Length; i++)
{
     command.Parameters.AddWithValue(nameTags[i], names[i]);
}
SQLiteDataReader reader = command.ExecuteReader();

while(reader.Read())
{
     Console.WriteLine(reader[0]);
}
0

精彩评论

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