方法错误,mysql

本文关键字:mysql 错误 方法 | 更新日期: 2023-09-27 18:17:19

我已经编码函数如下,我得到错误,我试图通过此方法从DB获得项目详细信息返回字符串。

    public static string GetItemDetails(int i_id, string i_name)
    {
        MySqlConnection SQL_con = new MySqlConnection(VPconfig.sql_conns);
        string[] ItemData = null;
        i_name = i_name == null ? string.Empty : i_name;
        i_id = i_id == 0 ? 0 : i_id;
        try
        {
            if(i_id != 0)
            {
                //get Item details by ID
                string query = "SELECT * FROM items WHERE id="+i_id;
                MySqlCommand xv = new MySqlCommand(query, SQL_con);
                SQL_con.Open();
                MySqlDataReader rdr = xv.ExecuteReader();
                while(rdr.Read())
                {
                    ItemData[0] = rdr.GetString("id");
                    ItemData[1] = rdr.GetString("iname");
                    ItemData[2] = rdr.GetString("iprice");
                }
                SQL_con.Close();
                string master = ItemData[0] +"*"+ ItemData[1] +"*"+ ItemData[2];
                return master;//Return format ID*NAME*PRICE
            }
            else if(i_name != string.Empty)
            {
                //get Item details by Name
                string query = "SELECT * FROM items WHERE iname=" + i_name;
                MySqlCommand xv = new MySqlCommand(query, SQL_con);
                SQL_con.Open();
                MySqlDataReader rdr = xv.ExecuteReader();
                while (rdr.Read())
                {
                    ItemData[0] = rdr.GetString("id");
                    ItemData[1] = rdr.GetString("iname");
                    ItemData[2] = rdr.GetString("iprice");
                }
                SQL_con.Close();
                string master = ItemData[0] + "*" + ItemData[1] + "*" + ItemData[2];
                return master;//Return format ID*NAME*PRICE
            }
            else
            {
                MessageBox.Show("No Items! found with ID/Name: " + i_id + i_name);
            }
            //if nothing
            return null;
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error Code: 17 "+ex.Message);
            //if nothing
            return null;
        }

现在,如果我传递以下参数显示错误"错误代码:17对象引用未设置为对象的实例。"这基本上来自catch

string xv = VPfunctions.GetItemDetails(5, string.Empty);
ta.Text = xv;

谢谢。

方法错误,mysql

抛出异常,因为您声明字符串数组为null,然后在DataReader循环中为其赋值。

那么,这一行:

string[] ItemData = null;

应该改成这样:

string[] ItemData = new string[5];