I am looking for a solution to insert some data in a a table using 3 parameters, the first one is the table name, and the second is a List with a class that has the name and value property.
I have a partially solution (below) for this, but i don’t think it is recommended, so, I looking for a best practice to do it.
If is possible, I’d like a suggestion to create this using parameters in order to avoid injections.
private void InsertMetada(string deviceType, List<DeviceFields> deviceFields)
{
DataBaseConnection database = new DataBaseConnection ();
database.Open();
StringBuilder strb = new StringBuilder();
stb.Append(string.Format("INSERT INTO DEVICE_{0} ( ", deviceType.ToString().ToUpper()));
foreach (var item in deviceFields)
{
strb.Append(string.Format(" {0}, ",item.name.ToString()));
}
stb.Append(") VALUES ( ");
foreach (var item in deviceFields)
{
strb.Append(string.Format(" '{0}', ", item.value.ToString()));
}
strb.Append(")");
database.executeQuery(strb.ToString());
database.Close();
}
EDITED: I don’t think I was very clear in my question.
In this case, the DeviceFields.item.name has the same name of the table field.
What I am looking for is guarantee create different Device properties, for different Device Types in different tables.
Maybe my point of view is not the right one, but I thought if I have separated tables I could perform a fast search.
In this example my Table (DEVICE_KEYBOARD) looks like this:
> FIELD NAME | TYPE
-------------|---------
language | varchar
key | varchar
isMultimedia | varchar
deviceID | varchar
and the list looks like
> DeviceFields[0]:
name = language
value = en-us
> DeviceField[1]:
name = key
value = 102
> DeviceField[2]:
name = isMultimedia
value = Yes
> DeviceField[3]:
name = deviceID
value = 0000-0000-00000-00000
And the second Table, for example is like:
TABLE DEVICE_SPEAKER
> FIELD NAME | TYPE
--------------|---------
rms | varchar
remoteControl | varchar
subwoofer | varchar
deviceID | varchar
It has all device fields in the first table, but this properties are specific for each kind of device…
The idea is to have opportunity to create a new property crating a new column, when the ADD button is clicked by the user, in this table, with the prefix “DEVICE_{DEVICE TYPE}”
I can list all fields when I prepare the List, my question is to know if is there a best option to create this stuff, and what could be safe and fast.
I agree with creating a stored procedure. If you need your INSERT statements to be dynamic, this can be done within the sproc.
http://www.codeproject.com/KB/database/Building_Dynamic_SQL.aspx
Personally, I hate dynamic SQL in stored procedures and some would say it is bad practice, but sometimes it is the best option depending on your circumstances. I’m just throwing it out there as an option.