Jony Jony - 5 months ago 14
SQL Question

Parameter '?...' has already been defined

I found some solutions and suggestions on the Internet concering this problem, however, I could not yet manage to apply this to my solution. I wrote a personal MySQL wrapper which features this

public async Task<IEnumerable<DatabaseFieldSet>> QueryParamsAsync(string query, string[] parameter,
string[] value)
{
if (!IsConnected)
await ConnectAsync();
var rows = new List<DatabaseFieldSet>();

using (var cmd = CreateCommand(query))
{
foreach (var str in parameter)
{
foreach (var val in value)
{
//cmd.Parameters.Add(str, MySqlDbType.VarChar).Value = val;
cmd.Parameters.AddWithValue(str, val);
}
}
using (var reader = await cmd.ExecuteReaderAsync())
{
uint currentRowIndex = 0;

while (await reader.ReadAsync())
{
var row = new DatabaseFieldSet(currentRowIndex);
var fields = new List<DatabaseField>();

for (var i = 0; i < reader.FieldCount; ++i)
{
var column = new DatabaseReference((uint) i);
fields.Add(new DatabaseField(reader[i], column, row));
}

row.Fields = fields;
rows.Add(row);

currentRowIndex++;
}
}
}

return rows;
}


I tried to add

cmd.Parameters.Clear();


at different locations, none worked or was throwing fatal error while executing. I hope somebody can tell me where to put this single statement.

Answer

You are doing it wrong. It rather should be like below. Your double foreach causing the issue and you are eventually trying to add the same parameter again and so the error. You rather should define a counter variable and access every item in your value array.

        int i = 0;
        foreach (var str in parameter)
        {
                cmd.Parameters.AddWithValue(str, val[i]);
                i++;
        }
Comments