Reputation: 2321
Hello I'm running into an error for my update function to a SQL database table. The error is:
Error: Operand type clash: text is incompatible with smallint
And I have no idea what is wrong there should be no values of type int
anywhere. All the inputs are strings and the table column type are all text. The update function is this:
public static void UpdateRows(string table, string columnToGet, string columnValueGet, string columnToSet, string columnValueToSet)
{
try
{
SqlConnection connection = new SqlConnection(Global.connectionString);
string updateString = "UPDATE " + table + " " + "SET " + columnToSet + "=" + columnValueToSet + " WHERE " + columnToGet + "=" + columnValueGet;
Console.WriteLine(updateString);
using (SqlCommand cmd = new SqlCommand(updateString, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("@" + columnToSet, "'" + columnValueToSet + "'");
cmd.Parameters.AddWithValue("@" + columnToGet, "'" + columnValueGet + "'");
cmd.ExecuteNonQuery();
connection.Close();
}
}
catch (SqlException ex)
{
Console.WriteLine("Error: " + ex.Message);
throw;
}
}
The console outputs a string like this :
UPDATE parentDirectory SET Child1ID=50042 WHERE ParentID=10020
And then the error appears. What is wrong? I've tried added "'" characters for the value variables, then I get a different error. I've got my Insert function sort of in the same format somewhere else and it works fine. Please help.
Upvotes: 1
Views: 912
Reputation: 13561
The column name should not be a parameter. By having the parameter include the column name columnValueToSet gets treated as a number. PS: this looks like a fishy design. PPS: it also opens it up to SQL injection.
public static void UpdateRows(string table, string columnToGet,
string columnValueGet, string columnToSet, string columnValueToSet)
{
try
{
SqlConnection connection = new SqlConnection(Global.connectionString);
string updateString =
"UPDATE " + table + " " +
"SET " + columnToSet + "= @columnValueToSet " +
"WHERE " + columnToGet + "= @columnValueGet;";
Console.WriteLine(updateString);
using (SqlCommand cmd = new SqlCommand(updateString, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("@columnValueToSet", columnValueToSet);
cmd.Parameters.Add("@columnValueGet", SqlDbType.Text).Value= columnValueGet;
cmd.ExecuteNonQuery();
connection.Close();
}
}
catch (SqlException ex)
{
Console.WriteLine("Error: " + ex.Message);
throw;
}
}
EDIT: As GarethD pointed out, the key problem is that parentId is defined as Text and there's no conversion between Text and int (there is between varchar and int, but not Text and int).
Upvotes: 2