datareader.read()只返回一个值

hivapdat  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(375)

我试图从一个有2行的mysql表中检索数据,但是只返回第一行。使用的sql语句非常简单sqlquery=“select*from table”
对于下面的代码,类只返回找到的第一个值

private ArrayList dbRead(String sqlQuery, String classQuery)
    {
        ArrayList dbCategoryResults = new ArrayList();

    //***CONNECT TO DATABASE
        Console.WriteLine("**Database Connection: Connecting to database");
        MySqlConnection dbConnection = new MySqlConnection(dbStringConnection);

        try
        {
            dbConnection.Open();
            Console.WriteLine("**Database Connection: Connected to database server");

            //***READ FROM DATABASE
            MySqlCommand command = new MySqlCommand(sqlQuery, dbConnection);
            MySqlDataReader dataReader = command.ExecuteReader();

            if (dataReader.Read())
            {
                if (classQuery == "categories")
                {
                    //String det = dataReader[1].ToString();

                    dbCategoryResults.Add(dataReader[1]);

                    Console.WriteLine("Found " + dbCategoryResults.Count);

                    return dbCategoryResults;
                }
            }
            dataReader.Close();

            command.Dispose();
            dbConnection.Close();
        }
        catch (MySqlException e)
        {
            Console.WriteLine(e.ToString());
            MessageBox.Show(e.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        // CLOSE DATABASE
        try
        {
            dbConnection.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        return null;
    }
t9aqgxwy

t9aqgxwy1#

就这么简单

// Always call Read before accessing data.
// Advances the MySqlDataReader to the next record.
// returns true if it finds a record
while (dataReader.Read()) 
{
   // depending on your query
   Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}

如果需要行数,可以使用 DataTable 或者在while循环中使用count。数据表示例:

DataTable dt = new DataTable();
dt.Load(reader);

Console.WriteLine("Rows returned : " + dt.Rows.Count); 

foreach(DataRow dr in dt.Rows)
{
     Console.WriteLine(dr["SomeResultingColumn"]);
}

相关问题