I have this method:
public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId)
{
sql = string.Format("UPDATE Phrase SET " + phraseColumn.Text() + " = {0} WHERE PhraseId = '{1}'", value, phraseId);
App.DB.RunExecute(sql);
}
It's not working correctly as it seems like I need the value of {0} needs to be a 0 or a 1.
Is there a simple way that I can take value and change it to be a 0 or a 1?
You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .
Boolean values and operations C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.
bool values are convertible to int type, with true converting to 1 and false converting to 0 .
You can multiply the return Boolean values (TRUE or FALSE) by 1, and then the TRUE will change to 1, and FALSE to 0. Assuming the original formula is =B2>C2, you can change it to =(B2>C2)*1. Note: You can also divide original formula by 1 or add 0 to original formula to change the return TRUE to 1 and FALSE to 0.
Just do value ? 1 : 0
, it's that easy!
@Sean has given to you the natural fix to your problem, but, in my view, what you really need to do here is to refactor your App.Db.RunExecute to receive parameters, so you can write
public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId)
{
sql = "UPDATE Phrase SET " + phraseColumn.Text() + " = @v WHERE PhraseId = @id";
List<SqlParameter> prms = new List<SqlParameter>
{
new SqlParameter {ParameterName = "@v", SqlDbType = SqlDbType.Boolean, Value = value},
new SqlParameter {ParameterName = "@id", SqlDbType = SqlDbType.NVarChar, Value = phraseId}
};
App.DB.RunExecute(sql, prms);
}
This will partially remove the Sql Injection problem (I say partially because that phraseColumn.Text() is still source of concerns if its value comes from the user input)
Now RunExecute should change to
void RunExecute(string sqlCommand, List<SqlParameter> prms = null)
{
// usual code to open connection and create a command
......
// If the caller passes a parameters list, add them to the command
if(prms != null)
cmd.Parameters.AddRange(prms.ToArray());
// Now execute the command
cmd.ExecuteNonQuery();
}
The change to RunExecute uses an optional argument, so your current code is not affected by the presence of the new argument but you will be able to write better Sql code from now on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With