Dillinger Dillinger - 4 years ago 146
Vb.net Question

How to remove a specific parameter in MySqlCommand?

I'm trying the parameter called

@idp
from my parameters list. In particular I've the following code:

Using dbCon As MySqlConnection =Connection()

dbCon.Open()

query = "INSERT INTO user (id_users, GUID)
VALUES(@idp, @guidp)"

MyCommand = New MySqlCommand(query, dbCon)

MyCommand.Parameters.AddWithValue("@user_id", 4) 'Parameter to replace in the next time
MyCommand.Parameters.AddWithValue("@guidp", GUID)

... There is other parameter here I reduce in this example

MyCommand.ExecuteNonQuery()

MyCommand.Parameters.AddWithValue("@idp", 5) 'Should replace the @idp but doesn't
Sync(MyCommand)

End Using


Now my query is just an example, I've a very long list of parameters so I don't want create redundant code. My application perform the insert in a local db and in online db. In the
Sync
function I pass the
MyCommand
as parameter and use
.Clone
for replicate the exact query in the online db. The problem's that in this specific case I've a constraint on this table, so I can't use the
LastInsertedId
of the query executed in the above code. For avoid this situation I've save a global variable that can be used in any class, this variable is used in the replaced parameter, but here for show what I want to achieve I just replace the variable name as
5
value, here:

MyCommand.Parameters.AddWithValue("@idp", 5)


How I can replace the parameter
@idp
with my
5
value instead of
4
without execute a
.Parameters.Clear
and redeclare all the parameters already use?


If something is unclear, tell me and I'll explain.

Answer Source

Don't use AddWithValue. If you create parameters you can use Remove to exclude one without Clear(). (caveat: I don't use MySQL so this syntax may not be exact)

MySqlParameter parUserId = new MySqlParameter("@user_id", MySqlDbType.Int32);
parUserId.Value = 5;
MyCommand.Parameters.Add(parUserId);
later....
MyCommand.Parameters.Remove(parUserId);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download