Foreach MySql表

时间:2016-03-25 04:41:31

标签: c# mysql

我已经连接到我的MySQL数据库并且已经在我的代码中直接输入命令接收输出,但我想添加一个功能,它会询问您在运行时期间要查询的命令。然后我希望它为每个执行一个并检索运行时查询中引用的所有数据。这是我的代码ATM,我收到错误。

try
        {
            con.Open();
            Console.WriteLine("Connection Open!");

            Console.WriteLine("Enter Query:");
            comString = Console.ReadLine();

            try
            {
                MySqlDataReader myReader = null;
                MySqlCommand myCommand = new MySqlCommand(comString, con);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    //Console.WriteLine(myReader["ID"].ToString() + " | " + myReader["NAME"].ToString() + " | " + myReader["PERMISSIONS"].ToString());
                    foreach (string i in myReader)
                    {
                        Console.WriteLine(myReader["i"].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

修改

这是我在

下面收到的错误
System.InvalidCastException: Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.String'.

在C:\ Pathssss \ sqlConnection \ sqlConnection \ Program.cs中的sqlConnection.Program.Main(String [] args):第50行

3 个答案:

答案 0 :(得分:1)

那是因为在foreach声明中您试图将object投射到string。使用此代码替换while块。

int count = myReader.FieldCount;
while(myReader .Read()) 
{
    for(int i = 0 ; i < count ; i++) 
    {
        Console.WriteLine(myReader.GetValue(i));
    }
}

答案 1 :(得分:0)

如果您有能力使用库,我建议使用Dapper,这将使您的生活更轻松。

用小巧玲珑你所要做的就是:

bool firstRun = true;
foreach(var result in con.Query(comString))
{
   var rDictionary = (IDictionary<string,object>)result;

   //assuming this is what you want based off of your commented out code
   if(firstRun){
       firstRun = false;
       Console.Write(string.Join("|",rDictionary.Keys));
   }

   Console.WriteLine( 
           string.Join("|", rDictionary.Select(a=>a.Value ?? (object)"NULL").ToArray())
   );
}

答案 2 :(得分:0)

我想建议你做另一种(我认为更好)的方法:

    try
    {
        con.Open();
        Console.WriteLine("Connection Open!");

        Console.WriteLine("Enter Query:");
        comString = Console.ReadLine();
        MySqlCommand myCommand = new MySqlCommand(comString, con);
        MySqlDataAdapter msda = new MySqlDataAdapter(myCommand);
        DataSet ds = new DataSet();
        msda.Fill(ds);
        foreach (DataRow dr in ds.Tables[0].Rows)
            Console.WriteLine(dr["column"].ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        con.Close();
    }