简体   繁体   English

在C#中通过SqlDataAdapter和DataSet更新

[英]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"); 我收到一条错误消息, 指出数据类型text和var char在等于运算符中不兼容,但错误指向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. 而且我很确定数据库连接已打开,因为我已经通过打印连接状态检查了它。

This won't work anyway unless you have specified an Update-Command for the DataAdaper . 除非您为DataAdaper指定了Update-Command,否则这将无法工作。

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();
}

The problem is in your select, because you can use the syntax, that Room = 'something' , because text is not compatible with =. 问题在于您的选择,因为可以使用语法Room = 'something' ,因为文本与=不兼容。

Use LIKE instead of equal sign (=) . 使用LIKE代替等号(=)

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. 但是我建议使用SqlParameters而不是string.Format ,因为它不安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM