Question

I have the fol code

 string user = "new user";
 DataSet myDS = new DataSet();
        string sql = string.Format("Select Counter,Occupants From Rooms where Room = '{0}'",room);
        SqlDataAdapter dAdapt = new SqlDataAdapter(sql, cnn);
        dAdapt.Fill(myDS, "Rooms");

        foreach (DataTable dt in myDS.Tables)
        {
            int var =(int) dt.Rows[0].ItemArray[0];
            var--;
            dt.Rows[0].ItemArray[0] = var;
            String occups = dt.Rows[0].ItemArray[1].ToString();
            occups += user;
            dt.Rows[0].ItemArray[1] = occups;
        }
        dAdapt.Update(myDS,"Rooms");  

I'm retrieving a single row with two columns-- Counter(small int type) and Occupants(text type). I get an error saying that the data types text and var char are incompatible in the equal to operator But the error is pointed to the line dAdapt.Fill(myDS, "Rooms"); which is weird. What's wrong here? And I'm pretty sure that the db connection is open as I've checked it by printing the connection status.

Was it helpful?

Solution 2

The problem is in your select, because you can use the syntax, that Room = 'something', because text is not compatible with =.

Use LIKE instead of equal sign (=).

Fixed query should look like:

SELECT Counter,Occupants FROM Rooms WHERE Room LIKE '{0}'

But I recommand to use SqlParameters instead of string.Format, because it is not secure.

OTHER TIPS

This won't work anyway unless you have specified an Update-Command for the DataAdaper.

I would not load the record into memory to update it. Meanwhile it could have been changed from another transaction. It's inefficient anyway. Instead i would use a single update-command:

string updateSql = @"
    UPDATE ROOMS SET
        Counter = Counter + 1,
        Occupants = Occupants + ',' + @newUser
    WHERE
        Room = @Room";

using(var con = new SqlConnection(connectionString))
using (var updateCommand = new SqlCommand(updateSql, con))
{
    updateCommand.Parameters.AddWithValue("@newUser", user);
    updateCommand.Parameters.AddWithValue("@Room", room);
    con.Open();
    updateCommand.ExecuteNonQuery();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top