ASP.以编程方式更新sql表行

本文关键字:sql 表行 更新 方式 编程 ASP | 更新日期: 2023-09-27 17:50:58

我有一个数据管道类,我想在其中创建一个更新方法,该方法接受参数名称、参数值和存储过程名称的列表。在执行时,我想更新sql db中的某一行。

目前为止在数据管道类中的代码是:

public class clsDataConduit
{
    SqlConnection Conn= new SqlConnection();
    SqlDataReader rdr= null;
    SqlDataAdapter dataChannel = new SqlDataAdapter();
    SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
    SqlCommand cmd = null;
    List<SqlParameter> SQLParams = new List<SqlParameter>();
    DataTable queryResults = new DataTable();
    DataRow newRecord;

        public void NewRecord(string SProcName)
        {
           //works fine
        }

        public void UpdateRecord(string SProcName)
        {
        Conn= new SqlConnection(connectionString);
        //open the database
        Conn.Open();
        //initialise the command builder for this connection
        SqlCommand dataCommand = new SqlCommand(SProcName, Conn);
        //add the parameters to the command builder
        //loop through each parameter
        for (int Counter = 0; Counter < SQLParams.Count; Counter += 1)
        {
            //add it to the command builder
            dataCommand.Parameters.Add(SQLParams[Counter]);
        }
        dataCommand.CommandType = CommandType.StoredProcedure;
        dataChannel = new SqlDataAdapter(SProcName, Conn);
        dataChannel.UpdateCommand = dataCommand;
        commandBuilder = new SqlCommandBuilder(dataChannel);
        dataChannel.Update(queryResults);
        ///////////////////////////////////////////////////////////
        // Method runs fine till above code, BUT I am not too sure 
        // how to write the rest of the code so that It updates a 
        // a particular row in sql
        ///////////////////////////////////////////////////////////
        //get the structure of a single record
        //newRecord = queryResults.NewRow();   //from previous method - new data

        Conn.Close();
        }
}

我不太确定如何从这一点继续下去。如果有人能帮助我,请。

谢谢

ASP.以编程方式更新sql表行

如果我正确理解了你的代码,你已经用适当的参数填充了命令(已经设置了值),所以你只需要调用

dataCommand.ExecuteNonQuery();

这就是您所需要的(当然,SQLParams列表应该已经填满了参数及其值)。另外,为了更通用,可以将SqlParameter列表传递给UpdateRecord,用于名为

的存储过程。
public void UpdateRecord(string SProcName, List<SqlParameters> prms)
{
    using(Conn= new SqlConnection(connectionString))
    {
        //open the database
        Conn.Open();
        //initialise the command builder for this connection
        SqlCommand dataCommand = new SqlCommand(SProcName, Conn);
        //add the parameters to the SqlCommand
        dataCommand.Parameters.AddRange(prms.ToArray());
        dataCommand.CommandType = CommandType.StoredProcedure;
        dataCommand.ExecuteNonQuery();
    }
}