Sql Parameter function help
Posted on 2003-10-23
Ok I've had it with trying to figure this one out :P
What I need is a generic function that will accept a t-sql string like the following:
sql = "select * from contest where field = @field and field2 = @field2";
it will then accept a hashtable that contains the values for the parameters like so:
Hashtable ht = new Hashtable();
So far I've gotten the following two functions.
public void Insert(Hashtable ht)
SqlDataAdapter sd = new SqlDataAdapter();
sd.InsertCommand = this.myConnection.CreateCommand();
sd.InsertCommand.CommandText = this.sql;
private void _addParams( SqlCommand cmd, Hashtable ht)
IDictionaryEnumerator myEnum = ht.GetEnumerator();
cmd.Parameters.Add("@" + myEnum.Key.ToString(), myEnum.Key.ToString());
cmd.Parameters["@" + myEnum.Key.ToString()].Value = myEnum.Value.ToString();
I believe the second function works ok. It reads from the hashtable and adds the parameters correctly. But the first one is too specific. I would even accept several functions i.e. one for insert one for select one for delete. But I'd prefer just one.
If anyone has the code out there or could modify this please do.