Parameterized Query for MySQL with C#
Try this instead:
private String readCommand =
"SELECT LEVEL FROM USERS WHERE VAL_1 = @param_val_1 AND VAL_2 = @param_val_2;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.AddWithValue("@param_val_1", val1);
m.Parameters.AddWithValue("@param_val_2", val2);
level = Convert.ToInt32(m.ExecuteScalar());
return true;
}
MySQL parameterized query is functioning like it is not parameterized in C# application
You should use the name of the column Gherkin
inside the function VALUES()
and not the named parameter ?Gherkin
:
UPDATE Gherkin = VALUES(Gherkin)
C# Parameterized Query MySQL with `in` clause
You could build up the parametrised query "on the fly" based on the (presumably) variable number of parameters, and iterate over that to pass them in.
So, something like:
List foo; // assuming you have a List of items, in reality, it may be a List<int> or a List<myObject> with an id property, etc.
StringBuilder query = new StringBuilder( "UPDATE TABLE_1 SET STATUS = ? WHERE ID IN ( ?")
for( int i = 1; i++; i < foo.Count )
{ // Bit naive
query.Append( ", ?" );
}
query.Append( " );" );
MySqlCommand m = new MySqlCommand(query.ToString());
for( int i = 1; i++; i < foo.Count )
{
m.Parameters.Add(new MySqlParameter(...));
}
c# mysql insert statement. Parameterized query example?
You could try to specify MySQLDbType
to match your DB Type and use Add
function:
cmd.Parameters.Add("?apellido", MySqlDbType.VarChar).Value = usuario.apellido;
How to get query with parameters form MySqlCommand
This is not tested and not complete, consider it more psuedo code to give you an idea.
You could write a utility method that takes a command, replaces the parameter placeholders with parameter values, then logs the query.
public static void LogCommand(MySqlCommand cmd)
{
string cmdText = cmd.CommandText;
foreach(MySqlParameter p in cmd.Parameters)
{
cmdText = cmdText.Replace(p.ParameterName, p.Value);
}
Log(cmdText); // <-- or however you are logging....
}
Related Topics
When to Use Static Classes in C#
Is There a Difference Between "Throw" and "Throw Ex"
Input String Was Not in a Correct Format
Simple Insecure Two-Way Data "Obfuscation"
Direct Casting VS 'As' Operator
C# Datetime to "Yyyymmddhhmmss" Format
How to Get the Type of T from a Member of a Generic Class or Method
Create a Strongly Typed C# Object from Json Object With Id as the Name
In C#, Should I Use String.Empty or String.Empty or "" to Intitialize a String
How to Await an Event Instead of Another Async Method
No Connection Could Be Made Because the Target Machine Actively Refused It
Using New Unity Videoplayer and Videoclip API to Play Video
String.Replace (Or Other String Modification) Not Working
Calling the Base Constructor in C#
Why Are Cdecl Calls Often Mismatched in the "Standard" P/Invoke Convention