我想将列表框项插入到数据库中,其中数据库值应该是从其他表中获取的整数

时间:2016-12-13 06:06:47

标签: c# sql-server webforms

我是C#的新手。请帮我构建查询

for (int i = 0; i < lstCountry.Items.Count; i++)
{
    if (lstCountry.Items[i].Selected == true)
    {
        cmd.CommandText = "INSERT ModuleMaster (ModuleName, Country, ModuleLeader, FirstAml, SecondAml,CoreTeamMember) VALUES (@ModuleName,@Country, @ModuleLeader, @FirstAml, @SecondAml, @CoreTeamMember)"
        + "SELECT * FROM CountryMaster WHERE CountryName IN (" + lstCountry + ");";

        cmd.Connection = sqlConnection1;

        cmd.Parameters.AddWithValue("@ModuleName", txtModuleName.Text);
        cmd.Parameters.AddWithValue("@Country",  lstCountry.Items[i].ToString() );
        cmd.Parameters.AddWithValue("@ModuleLeader", ddModuleLeader.Text);
        cmd.Parameters.AddWithValue("@FirstAml", ddFirstAML.Text);
        cmd.Parameters.AddWithValue("@SecondAml", ddSecondAML.Text);
        cmd.Parameters.AddWithValue("@CoreTeamMember", txtCoreMembers.Text);

        sqlConnection1.Open();
        cmd.ExecuteNonQuery();
        sqlConnection1.Close();
    }
}

这是我开发的查询。

提前致谢

1 个答案:

答案 0 :(得分:0)

据我所知,你需要这样的东西

using (var connection = new SqlConnection(connectionString))
 {
    using (var cmd = connection.CreateCommand())
     {
        var selected_item = lstCountry.SelectedItem.ToString();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "INSERT ModuleMaster (ModuleName, Country, ModuleLeader, FirstAml, SecondAml, CoreTeamMember) "
                       + $"SELECT ModuleName, Country, ModuleLeader, FirstAml, SecondAml, CoreTeamMember FROM CountryMaster WHERE CountryName = {selected_item}";
        connection.Open();
        cmd.ExecuteNonQuery();
        connection.Close();
     }
 }