(My VB is very rusty, bear with me...)
Presumably you have a couple of values. Specifically a table name and a collection of key/value pairs representing column names and column values. Using these, you can dynamically build the string for your query.
Start with the basic structure of the query. Something like this:
Dim query As New StringBuilder()
query.Append("INSERT INTO ")
' TODO: append table name
query.Append(" (")
' TODO: append column names (loop)
query.Append(") VALUES (")
' TODO: append parameter names (loop)
query.Append(")")
Dim MyCommand As New MySqlCommand(query.ToString(), someConnection)
' TODO: append actual parameters (loop)
Let's go through each of the TODO components one at a time...
1. The table name is the easy part, since no looping is involved. Assuming it's in a variable:
query.Append(someTableName)
2. You can tweak performance of the various loops, but for simplicity right now let's just loop over the key/value pairs three times. (We'll actually use built-in methods which internally have loops, but the point remains.) For the column names, let's assume you have an array of strings:
query.Append(string.Join(",", someColumnNamesArray))
(Note: The reason to use string.Join() instead of manually looping is to avoid having to do some potentially ugly logic for whether or not to include the "," separator for first/last entries.)
3. And for the parameter names, just use numbers. I don't know if parameters are allowed to begin with a digit, so to play it safe let's arbitrarily have them begin with an "a" and then the digit. You can use Enumerable.Range() to get a list of integers the length of your array. So something like this:
query.Append(string.Join(",", Enumerable.Range(0, someColumnNamesArray.Count()).Select(Function(x) string.Format("@a{0}", x))))
It's kind a complex-looking piece of code, I admit. But what it basically does is:
- Create a range of integers from 0 to the length of the array of column names.
- Select a formatted string based on those integers, creating a list of strings like
"@a0", "@a1", and so on.
- Use
string.Join() to turn that list into a single comma-separated string.
Feel free to do that on multiple lines if it looks cleaner to you.
At that point you should have your query. Something like this:
"INSERT INTO someTable (someColumn, anotherColumn, andAnother) VALUES (@a0, @a1, @a2)"
4. Then you can loop over your array of values to add your parameters:
For i As Integer = 1 To someValuesArray.Count()
MyCommand.Parameters.AddWithValue(string.Format("@a{0}", i), someValuesArray[i])
Next