【问题标题】:Get Value of Tuple From MySQL into String Array从 MySQL 获取元组的值到字符串数组中
【发布时间】:2014-04-12 18:48:07
【问题描述】:

我想从数据库中选择所有行和列(没有条件)并将每个元组(例如:表中 index[0,0] 的值)存储在一个字符串数组中..

这是我正在使用的代码:

using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection("S;Port=P;Database=DB;Uid=U;Pwd=P"))                      {
       connection.Open();
       MySql.Data.MySqlClient.MySqlCommand cmd=connection.CreateCommand();
       cmd.CommandText = "SELECT * FROM table_name";
       MySql.Data.MySqlClient.MySqlDataReader datr = cmd.ExecuteReader();            
       coun = Convert.ToInt32(cmd.ExecuteScalar());
       while (datr.Read()){
            for (int i = 0; i < coun; i++)  {                          
                 First_String[i] = datr[0].ToString();
                 Second_String[i] = datr[1].ToString();
                Third_String[i] = datr[2].ToString();
                        /* and so on...*/   
             }
       }
}

我收到一条错误消息:Object not "Object reference not set to an instance of an object."

做错了什么?

谢谢

【问题讨论】:

  • 内循环没有意义。您正在重复相同的数据计数。 While(data.Read()) 执行您尝试对内部循环执行的操作。
  • 确保初始化你的第一个、第二个和第三个数组,同时检查你的数据库是否存在空值
  • 哪一行抛出错误?因为并非所有代码都是可见的。
  • @Izzo32 在第二次 While 迭代中,Data 将被覆盖,因为 i 将再次为 0。
  • @Izzo32 like First_String=new string[column_count_of db_table]

标签: c# mysql visual-studio-2012 datareader


【解决方案1】:

试试这个代码

using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection("S;Port=P;Database=DB;Uid=U;Pwd=P"))                      {
       connection.Open();
       MySql.Data.MySqlClient.MySqlCommand cmd=connection.CreateCommand();
       cmd.CommandText = "SELECT * FROM table_name";
       MySql.Data.MySqlClient.MySqlDataReader datr = cmd.ExecuteReader();            
       coun = Convert.ToInt32(cmd.ExecuteScalar());
       int counter = 0;
       string[] First_String = new string[datr.FieldCount];
       string[] Second_String = new string[datr.FieldCount];
       string[] Third_String = new string[datr.FieldCount];
       while (datr.Read()){                          
                 First_String[counter] = datr[0].ToString();
                 Second_String[counter] = datr[1].ToString();
                Third_String[counter] = datr[2].ToString();
                        /* and so on...*/   
                counter++;
       }
}

【讨论】:

  • 我认为你没有初始化你的数组:/
  • 是的,我试过你的代码,我得到了同样的错误,但在代码末尾 >> counter++
  • 对象引用未设置为对象的实例。
  • 效果很好 :):) 非常感谢 Zohaib
【解决方案2】:

如果你经常使用 datareader,你可以使用这篇文章中的这个帮助类

SqlDataReader Best way to check for null values -sqlDataReader.IsDBNull vs DBNull.Value

/// <summary>
/// Helper class for SqlDataReader, which allows for the calling code to retrieve a value in a generic fashion.
/// </summary>
public static class SqlReaderHelper
{
    private static bool IsNullableType(Type theValueType)
    {
        return (theValueType.IsGenericType && theValueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }

    /// <summary>
    /// Returns the value, of type T, from the SqlDataReader, accounting for both generic and non-generic types.
    /// </summary>
    /// <typeparam name="T">T, type applied</typeparam>
    /// <param name="theReader">The SqlDataReader object that queried the database</param>
    /// <param name="theColumnName">The column of data to retrieve a value from</param>
    /// <returns>T, type applied; default value of type if database value is null</returns>
    public static T GetValue<T>(this SqlDataReader theReader, string theColumnName)
    {
        // Read the value out of the reader by string (column name); returns object
        object theValue = theReader[theColumnName];

        // Cast to the generic type applied to this method (i.e. int?)
        Type theValueType = typeof(T);

        // Check for null value from the database
        if (DBNull.Value != theValue)
        {
            // We have a null, do we have a nullable type for T?
            if (!IsNullableType(theValueType))
            {
                // No, this is not a nullable type so just change the value's type from object to T
                return (T)Convert.ChangeType(theValue, theValueType);
            }
            else
            {
                // Yes, this is a nullable type so change the value's type from object to the underlying type of T
                NullableConverter theNullableConverter = new NullableConverter(theValueType);

                return (T)Convert.ChangeType(theValue, theNullableConverter.UnderlyingType);
            }
        }

        // The value was null in the database, so return the default value for T; this will vary based on what T is (i.e. int has a default of 0)
        return default(T);
    }
}

用法:

yourSqlReaderObject.GetValue<int?>("SOME_ID_COLUMN");
yourSqlReaderObject.GetValue<string>("SOME_VALUE_COLUMN");

【讨论】:

    【解决方案3】:

    添加这个方法

    public static class DataReaderExtensions
    {
    
        public static string SafeGetString(this SqlDataReader reader, int colIndex)
        {
           if(!reader.IsDBNull(colIndex))
               return reader.GetString(colIndex);
           else 
               return string.Empty;
        }
    }
    

    把你的代码改成这个

    for (int i = 0; i < coun; i++)
    {
     First_String[i] = datr.SafeGetString(0);
     Second_String[i] = datr.SafeGetString(1);
     Third_String[i] = datr.SafeGetString(2);
    }
    

    【讨论】:

    • 你能设置一个断点并告诉我是哪一行导致了异常吗?
    • 您确定您的表格至少有 3 列吗?
    • @Izzo32 附注对于循环列,您不需要运行 coun = Convert.ToInt32(cmd.ExecuteScalar()); 只需使用 datr.FieldCount
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2018-12-21
    相关资源
    最近更新 更多