2013-05-08 69 views
0

我有下面的代码从数据库中选择记录:如何验证多列表

public List<string>[] Select(string Command) 
    { 
     string query = Command; 

     //Create a list to store the result 
     List<string>[] list = new List<string>[2]; 
     list[0] = new List<string>(); 
     list[1] = new List<string>(); 


     //Open connection 
     if (this.OpenConnection() == true) 
     { 
      //Create Command 
      MySqlCommand cmd = new MySqlCommand(query, connection); 
      //Create a data reader and Execute the command 
      MySqlDataReader dataReader = cmd.ExecuteReader(); 

      //Read the data and store them in the list 
      while (dataReader.Read()) 
      { 
       list[0].Add(dataReader["NIK"] + ""); 
       list[1].Add(dataReader["Password"] + "");      
      } 

      //close Data Reader 
      dataReader.Close(); 

      //close Connection 
      this.CloseConnection(); 

      //return list to be displayed 
      return list; 


     } 
     else 
     { 
      return list; 
     } 
    } 

我有2列在我的表,这是NIKPassword和表中有2行是112,1

如何验证列表是否包含NIK = 2和Password = 1?我如何知道select语句是否成功从我的表中获取记录?如何将多列表打印到文本框中?

回答

0

您应该考虑使用Dictionary<string, string>而不是List<string>的数组。

然后,您可以打印所有记录:

foreach (var pair in dictionary) 
    Console.WriteLine(pair.Key + ", " pair.Value); 

在每一个字典对第一个字符串是一个关键,第二个是一个值。

0

我如何验证列表是否包含NIK = 2和密码= 1?

查看列表并检查。例如,使用Enumerable.Any

如何知道select语句是否成功从我的表中获取记录?

如果没有抛出异常。

如何将多列表打印到文本框?

构建从(例如,使用StringBuilder)数据库返回的值的字符串,并将其分配给TextBox.Text


顺便说一句,你真的应该考虑封闭阅读器和连接在using块。这样,即使在例外的情况下,资源也将被确定性地释放。

此外,请考虑使用类型特定的getter从读取器读取数据(例如GetString,GetInt32等)。