【问题标题】:C# Foreach List , insert to sql databaseC# Foreach 列表,插入到 sql 数据库
【发布时间】:2017-10-07 08:07:33
【问题描述】:

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

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)");
     }
}

【问题讨论】:

  • 错误是什么?
  • 这段代码遇到了什么问题?
  • “foreach(npc in NpcAI.RegisteredNpc)”中的错误 Gravità Codice Descrizione Progetto File Riga Stato eliminazione Errore CS0030 Non è possibile convertire il tipo 'System.Collections.Generic.KeyValuePair>' 在“字符串”中。 Androm C:\Users\Stefano\Desktop\Andrest\Game\Npcs\NpcAI.cs 44 Attivo
  • 注意:正如另一个steve 所提到的,为什么要在字典中添加两个具有相同键“Ballons”的元素?这是什么CDictionnary 实现?再一次,这段代码的目的是什么?你的意思是用它做什么?
  • (欢迎来到 SO!)请不要评论 cmets 要求更多信息或澄清:编辑您的问题。

标签: c# list foreach


【解决方案1】:

你的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)");
    }
}       

【讨论】:

  • 注意:再次编辑,我的代码有语法错误。它现在应该可以工作了,只要你的 SqlDatabaseClient 工作正常
  • 如果 CDictionnary 真的是字典,我看不到如何使用相同的键“Ballons”添加两个元素
  • 你不会的。您将添加一个名称为“Ballons”的名称和另一个名称为“lons”的名称。那就是你的代码试图做的。你到底想要什么数据库?您希望插入后的数据库是什么样的?
  • 如果 CDictionnary 包含一些逻辑来合并具有相同键的列表,那么我们在保存列表数据的逻辑中存在问题
  • @Wndrr 键在 Add 行中,不在列表值中。我想。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多