Obtaining an Array with MysqlDataReader (Function)

1k views Asked by At

I have made Function that returns List<string>[] for mysql database by calling example[0][1] and I have to specify the Columns I wan't to fetch... i.e

dbConnect = new DBConnect();
List<string>[] userlogin;
List<MySqlParameter> parameters = new List<MySqlParameter>();
parameters.Add(new MySqlParameter("@Username", usernameinput.Text));
parameters.Add(new MySqlParameter("@Keya", passwordhashed));
dbConnect.Select("SELECT `id`, `Username`, `Key`, `AdminLevel`,`Model` FROM `accounts` WHERE `Username` = @Username AND `Key` = @Keya", parameters, 5, "Username", "AdminLevel", "Key", "id", "Model");

My Class

using System.Collections.Generic;
using MySql.Data.MySqlClient;
using System;

namespace something
{
class DBConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;
    public bool connectionstatus = false;

    //Constructor
    public DBConnect()
    {
        Initialize();
    }

    //Initialize values
    private void Initialize()
    {
        server = "127.0.0.1";
        database = "smth";
        uid = "root";
        password = "123123";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
        this.OpenConnection();
    }

    //open connection to database
    public bool OpenConnection()
    {
        if (connectionstatus != true)
        {
            try
            {
                connection.Open();
                connectionstatus = true;
                return true;
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based 
                //on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }
        return true;
    }

    //Close connection
    public bool CloseConnection()
    {
        if (connectionstatus == true)
        {
            try
            {
                connection.Close();
                connectionstatus = false;
                return true;
            }
            catch (MySqlException ex)
            {
                ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show(ex.Message);
                //MessageBox.Show(ex.Message);
                return false;
            }
        }
        return true;
    }
    public List<string>[] Select(string query, List<MySqlParameter> Values, int numofcolumns, params string[] columns)
    {
        string[] columns2 = columns;
        //numofcolumns -= 1;
        for (int i = 0; i < numofcolumns; i++)
            columns2[i] = string.Format("`{0,-3}`", columns[i]);

        string columns3 = string.Join(",", columns2);

        columns3 = Functions.TrimAllWithInplaceCharArray(columns3);

        //string query = "SELECT "+ columns3 + " FROM `"+ table + "` WHERE " + whereclause;

        //Create a list to store the result
        List<string>[] list = new List<string>[numofcolumns];
        for (int i = 0; i < numofcolumns; i++)
        {
            list[i] = new List<string>();
        }

        //Open connection
        if (connectionstatus == true)
        {
            //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);
            foreach (MySqlParameter param in Values)
            {
                cmd.Parameters.Add(param);
            }
            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();

            //Read the data and store them in the list
            while (dataReader.Read())
            {
                for (int i = 0; i < numofcolumns; i++)
                {
                    columns[i] = columns[i].Trim(new Char[] { ' ', '`' });
                    list[i].Add(dataReader[columns[i].ToString()].ToString());
                }
            }

            //close Data Reader
            dataReader.Close();

            //close Connection
            //this.CloseConnection();

            //return list to be displayed
            return list;
        }
        else
        {
            return list;
        }
    }
}
}

But what I wan't is a little Convenient.. i.e which I can use/call be saying example[0]["table"] and I don't have to specify the table for... i.e

dbConnect.Select("SELECT * FROM accounts WHERE Username = @Username AND Key = @Keya", parameters);

Please Specify the usage and The edits I need to make in my class...

1

There are 1 answers

0
Raja Bilal On BEST ANSWER

I have Solved my Question after some workaround for approximately 24 hours or some...

The Working Function

    //I have already Made the Connection and this is the Function/Method for the Class
    public Dictionary<string, string[]> Select(string query, List<MySqlParameter> Values)
    {

        //Open connection
        if (connectionstatus == true)
        {
            //MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection);
            MySqlCommand cmd = new MySqlCommand(query, connection);

            foreach (MySqlParameter param in Values)
            {
                cmd.Parameters.Add(param);
            }


            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();
            Dictionary<string, string[]> data = new Dictionary<string, string[]>();

            var table = new DataTable();

            do
            {
                table.Load(dataReader);
            } while (!dataReader.IsClosed);

            var columns = table.Columns.Cast<DataColumn>()
             .Select(x => x.ColumnName)
             .ToList();

            var totalrownum = table.Rows.Count;


            string[][] values = new string[columns.Count][];

            for (int i = 0; i < columns.Count; i++)
            {
                values[i] = new string[totalrownum];

            }
            for (int column = 0; column < columns.Count; column++)
            {
                for (int i = 0; i < totalrownum; i++)
                {
                    values[column][i] = table.Rows[i][column].ToString();
                }

                data.Add(columns[column], values[column]);
                Console.WriteLine(columns[column]);
            }
            //close Data Reader
            dataReader.Close();

            return data;
        }
        else
        {
            Dictionary<string, string[]> data = new Dictionary<string, string[]>();
            return data;
        }
    }

Once it's run it's Values can be used Easily...

            List<MySqlParameter> parametersdata = new List<MySqlParameter>();
            parametersdata.Add(new MySqlParameter("@Username", usernameinput.Text));
            parametersdata.Add(new MySqlParameter("@Keya", passwordhashed));

            Dictionary<string, string[]> usersdata = new Dictionary<string, string[]>();
            usersdata = dbConnect.Select("SELECT `id`, `Username`,`AdminLevel`,`Model`,`Level` FROM `accounts` WHERE `Username` = @Username", parametersdata);

            List<string> someList= new List<string>();
            someList.Insert(0,usersdata["Model"][0]);//Model
            someList.Insert(1,usersdata["Level"][0]);//Level
            someList.Insert(2,usersdata["AdminLevel"][0]);//Adminlevel-0 here is the row index