我有一个列表视图,其中包含要插入到SQL Server数据库中的项目

时间:2019-04-10 17:47:22

标签: c#

我想将列表视图的内容保存到SQL Server数据库中。

我尝试了注释的代码,但收到错误

  

必须声明标量变量@Description

代码:

private void btnFinish_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand();

    try
    {
        foreach (ListViewItem item in lvregion.Items)
        {
            SqlConnection conn;
            SqlCommand comm;

            string connectionString = ConfigurationSettings.AppSettings["conn"];
            conn = new SqlConnection(connectionString);

            comm = new SqlCommand(
              "INSERT INTO Region (RegionDescription, Fname, Lname) " +
              "VALUES (@RegionDescription, @Fname, @Lname)", conn);
            //cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
            //cmd.Parameters.AddWithValue("fname", item.SubItems[1].Text.Trim());
            //cmd.Parameters.AddWithValue("lname", item.SubItems[2].Text.Trim());
            cmd.Parameters.Add("RegionDescription", SqlDbType.VarChar,40);
            cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
            cmd.Parameters.Add("Fname", SqlDbType.VarChar,40);
            cmd.Parameters.AddWithValue("Fname", item.SubItems[1].Text.Trim());
            cmd.Parameters.Add("Lname", SqlDbType.VarChar,40);
            cmd.Parameters.AddWithValue("Lname", item.SubItems[2].Text.Trim());

            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:0)

欢迎使用Stackoverflow, 首先,我不建议在foreach中创建新连接以将项目添加到表中。 这是我建议使用的替代方法:

try
{
    string connectionString = ConfigurationSettings.AppSettings["conn"];
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        SqlCommand cmd;
        conn.Open();
        string cmdString = @"INSERT INTO Region (RegionDescription, Fname, Lname) 
                             VALUES (@RegionDescription, @Fname, @Lname)";

        foreach (ListViewItem item in lvregion.Items)
        {
            cmd = new SqlCommand(cmdString, conn);
            cmd.Parameters.Add("@RegionDescription", SqlDbType.VarChar, 40).Value = item.Text.Trim();
            cmd.Parameters.Add("@Fname", SqlDbType.VarChar, 40).Value = item.SubItems[1].Text.Trim();
            cmd.Parameters.Add("@Lname", SqlDbType.VarChar, 40).Value = item.SubItems[2].Text.Trim(); 
            cmd.ExecuteNonQuery();
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

(或者至少应该让您走上正确的路。)