Search code examples
c#sql-serverdatasetdataadapter

Updating through SqlDataAdapter and DataSet in C#


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.


Solution

  • 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.