2016-03-25 5 views
-1

私は自分のMySQLデータベースに接続しており、自分のコードに直接コマンドを入力して出力を受け取っていますが、実行時に特に照会するコマンドを尋ねる機能を追加します。それから私はそれを実行し、ランタイムクエリで参照されるすべてのデータを取得する必要があります。これは私のコードATMです。エラーが出ます。Foreach MySqlテーブル

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

EDIT

これは、iがCでsqlConnection.Program.Mainで

System.InvalidCastException: Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.String'. 

(文字列[]引数)より受信エラーである:\ Pathssss \のSQLConnection \ SqlConnectionの\プログラム。 cs:行50

+0

、これらのエラーを共有してください。 – Christoph

答えて

1

foreachの文では、objectstringにキャストしようとしているからです。 whileブロックを交換するには、このコードを使用してください。

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

私の友人は純粋な天才です! –

0

あなたは私がDapperを使用することをお勧めしたライブラリを使用する能力を持っている場合は、あなたの人生はずっと楽になります。 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()) 
    ); 
} 
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(); 
    }