使用 MysqlDataReader 获取数组(函数)

Obtaining an Array with MysqlDataReader (Function)

我通过调用 example[0][1] 为 mysql 数据库创建了 returns List<string>[] 的函数,我必须指定我不想获取的列...即

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

我的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;
        }
    }
}
}

但我想要的是有点方便.. 即我可以 use/call 说 example[0]["table"] 而且我不必为...指定 table 即

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

请在我的 class...

中指定用法和我需要进行的编辑

经过大约 24 小时或一些变通方法,我已经解决了我的问题...

工作函数

    //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;
        }
    }

一旦 运行 就可以轻松使用值...

            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