Reputation:
I have a C# property which is of data type bool
and when it gets set, it becomes a True
or False
.
However I need for it to match up with a SQL Server table column of type bit
so that it is saved as a 1 or 0.
SQL Server column:
StormOut bit
C# property
public bool StormOut { get; set; }
C# SQL statement:
string querystring = "UPDATE tblSignOnOff SET StormOut = " + storm.StormOut + " WHERE id = 1902";
Otherwise currently the SQL statement in C# is
UPDATE tblSignOnOff
SET StormOut = True
WHERE id = 1902
Which results in an error:
Invalid column name 'True'.
Upvotes: 6
Views: 17450
Reputation: 3131
Further modifying the answer from @S.Akbari with his suggestion for parameterized queries;
SqlCommand command = new SqlCommand();
command.CommandText = "UPDATE tblSignOnOff SET StormOut = @StormOut WHERE id = @id";
command.Parameters.AddWithValue("@StormOut", storm.StormOut);
command.Parameters.AddWithValue("@id", 1902);
Upvotes: -1
Reputation: 39946
You have missed single quotes. Change like this:
string querystring = "UPDATE tblSignOnOff SET StormOut = '" + storm.StormOut + "' WHERE id = 1902";
But an important note: You should always use parameterized queries
like below. This kind of string concatenations are open for SQL Injection
:
string querystring = "UPDATE tblSignOnOff SET StormOut = @StormOut WHERE id = @id";
yourCommand.Parameters.AddWithValue("@id", 1902);
yourCommand.Parameters.AddWithValue("@StormOut", storm.StormOut);
Upvotes: 6
Reputation: 2243
You should use parameters and avoid string concatenation
string Command = "UPDATE tblSignOnOff SET StormOut @StormOut WHERE id = @id";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
mConnection.Open();
using (SqlCommand myCmd = new SqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("@id", 1902); // TODO set this value dynamically
myCmd.Parameters.AddWithValue("@StormOut", storm.StormOut);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
Upvotes: 1