循环select命令时如何更新表?

时间:2016-11-06 07:35:09

标签: c# sql-server

string connString = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
try
{
    conn.Open();
    string cmdUpdate = "UPDATE mem SET name =@name";
    string cmd = "SELECT * FROM mem;";
    SqlCommand comm = new SqlCommand(cmd, conn);
    SqlCommand commUpdate = new SqlCommand(cmdUpdate, conn);
    SqlDataReader dr = comm.ExecuteReader();
    while (dr.Read())
    {
        DateTime date = DateTime.ParseExact(dr["date"].ToString(), "dd-MM-yyyy", CultureInfo.InvariantCulture);
        if (date < DateTime.UtcNow)
        {
            commUpdate.Parameters.Clear();
            commUpdate.Parameters.AddWithValue("@name", "Done");
            comm.ExecuteNonQuery();
        }
    }
    conn.Close();
}
catch (Exception ex) {
    MessageBox.Show(ex.ToString());
}

这是我的代码。

<connectionStrings>
    <add name="TestDatabase" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Test.mdf;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>

这是我的连接字符串。

我想在检索数据时更新名称并匹配条件。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

然后调用ExecuteReader以确保结果使用HasRows。此外,不是在循环的每次迭代中添加/清除参数,而是创建参数一次并重新使用它,如下所示。最后,选择仅需要的字段而不是SELECT * FROM。

是一种很好的形式
public class Demo
{
    public void Example()
    {
        string connString = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
        SqlConnection conn = new SqlConnection(connString);
        try
        {
            conn.Open();
            string cmdUpdate = "UPDATE mem SET name =@name";
            string cmd = "SELECT * FROM mem;";
            SqlCommand comm = new SqlCommand(cmd, conn);
            SqlCommand commUpdate = new SqlCommand(cmdUpdate, conn);
            SqlDataReader dr = comm.ExecuteReader();
            if (dr.HasRows)
            {
                comm.Parameters.Add(new SqlParameter() { ParameterName = "@name", DbType = System.Data.DbType.String });
                while (dr.Read())
                {
                    DateTime date = DateTime.ParseExact(dr["date"].ToString(), "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    if (date < DateTime.UtcNow)
                    {
                        commUpdate.Parameters["@name"].Value = "Done";
                        comm.ExecuteNonQuery();
                    }
                }
                conn.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

    }
}