1

接続は正常に機能しています。ただし、MysqlDataREADer dataReader 行を実行すると、ウィンドウ フォームが表示され、while ループにアクセスしてデータを取得しません。データベースからの情報を表示するために dataGridView を使用しています。私は何を間違えましたか?ありがとう

    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader= cmd.ExecuteReader();
        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader["id"] + "");
            list[1].Add(dataReader["name"] + "");
            list[2].Add(dataReader["weekday"] + "");
            list[3].Add(dataReader["description"] + "");
        }

        //close Data Reader
        dataReader.Close();

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

1 に答える 1

1

コマンドは何ですか?

Read() 関数は、リーダーを次のレコードに進めます。レコードが返されなかった場合、if はすぐに false になります。

そのため、コマンドは何も返さない可能性が最も高いです。次のようなことをしたいとします (HandleRecord は単にコードをきれいにするためのものです)。

if(reader.Read())
{
    // Handle first record
    HandleRecord(dataReader)
    while(reader.Read())
    {
         // Handle remaining records
         HandleRecord(dataReader)
    }
}
else
{
    // Nothing was returned, do something
}

また、例外を処理する必要があります。提供されたコードから、try-catch-finally ステートメントがないようです。私の記憶が正しければ、次のようになります。

 try
 {
     // Contact database - read/write/whatever
 }
 catch
 {
     // Display exception to user, log, whatever you need
 }
 finally
 {
     // Close database connection and other cleanup
 }
于 2013-02-19T04:19:15.753 に答える