for循环只写入我的mssql存储过程一次?

hlh*_*406 0 c# sql-server stored-procedures

我有一个for循环,它从我的C#Web表单中收集数据,并通过存储过程将它找到的每个项目写入数据库.

我遇到的问题是它只写了一次数据库.我已经逐步完成了visual studio中的代码并插入了测试变量来检查所有数据是否存在并且正在被捕获,这就是它.另外,因为第一次我知道它正在工作时存储过程正确执行.

所以我认为问题可能在于我如何在for循环中获得try catch?
或者可能是完全不同的东西 - 我真的可以用一双新鲜的眼睛和有人指出我正确的方向!

protected void log_hd_number()
{
    ////write results to DB.
    SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Integrated Security=True");
    SqlCommand cmd = conn.CreateCommand();
    SqlDataReader reader;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "insert_requested_hd";

    Dictionary<String, String> hdSize = new Dictionary<String, String>();

    hdSize.Add("hardDiskSizeData1", hardDiskSizeData1.Text);
    hdSize.Add("hardDiskSizeData2", hardDiskSizeData2.Text);

    int numberRequested = 2;

    for (int i = 1; i <= numberRequested; i++)
    {
        cmd.Parameters.AddWithValue("@hd_size", hdSize["hardDiskSizeData" + i]);
        cmd.Parameters.AddWithValue("@number_requested", numberRequested);
        cmd.Parameters.AddWithValue("@vm_id", 15);

        try
        {
            conn.Open();
            reader = cmd.ExecuteReader();
            reader.Close();
        }
        catch (Exception exc)
        {

        }
        finally
        {
            if (conn.State != ConnectionState.Closed)
                conn.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

SP:

ALTER PROCEDURE [dbo].[insert_requested_hd] 
    -- Add the parameters for the stored procedure here
    @hd_size nvarchar(150),
    @number_requested int,
    @vm_id int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO dbo.hard_disk_size
                (
                    hd_size,
                    number_requested,
                    vm_id
                )
    VALUES 
                (
                    @hd_size,
                    @number_requested,
                    @vm_id
                )
Run Code Online (Sandbox Code Playgroud)

FS'*_*hre 6

你不断在循环中向cmd添加参数而不清除旧的参数.也许这就是问题所在.

我也不确定你可以在它关闭后打开一个conn.我想你必须做一个新的.