C#Foreach List,插入到sql数据库

时间:2017-10-07 08:07:33

标签: c# list foreach

我尝试使用INSERT在数据库mysql上编写完整列表的错误代码。 用户如何正确地预测函数?

NpcAI.RegisteredNpc = new CDictionnary<string, List<string>>();
NpcAI.RegisteredNpc.Add("Ballons", new List<string>()
      {
        "1", //id
        "Ballons" // name
      });

NpcAI.RegisteredNpc.Add("Ballons", new List<string>()
      {
        "2", //id
        "lons" // name
      });



foreach(npc in NpcAI.RegisteredNpc)
{
     using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
     {
         client.ClearParameters(); 
         client.SetParameter("id", (object) npc[id]);
         client.SetParameter("name", (object) npc[name]; 
         client.ExecuteNonQuery("INSERT INTO `npc`(`id`, `name`) VALUES (@id, @name)");
     }
}

1 个答案:

答案 0 :(得分:0)

您的foreach应该如下声明:

foreach(KeyValuePair<string, List<string>> npc in NpcAI.RegisteredNpc)
{
    // code
}

只要没有SQL错误,这是您的完整编辑器和工作代码。

NpcAI.RegisteredNpc = new CDictionnary<string, List<string>>();

NpcAI.RegisteredNpc.Add("Ballons", new List<string>()
{
    "1", //id    
    "Ballons" // name
});

NpcAI.RegisteredNpc.Add("Ballons", new List<string>()
{
    "2", //id
        "lons" // name    
});


foreach(KeyValuePair<string, List<string>> npc in NpcAI.RegisteredNpc)
{

    using(SqlDatabaseClient client = SqlDatabaseManager.GetClient())
    {
        client.ClearParameters(); 
        client.SetParameter("id", npc.Value[0]); // will get the first value so it'll be 1 or 2
        client.SetParameter("name", npc.Value[1]); // will get the second value, so it'll be either "Ballons" or "lons"     
        client.ExecuteNonQuery("INSERT INTO `npc`(`id`, `name`) VALUES (@id, @name)");
    }
}