我正在尝试从具有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;
}
答案 0 :(得分:5)
这很简单
// 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循环中使用计数。 DataTable示例:
DataTable dt = new DataTable();
dt.Load(reader);
Console.WriteLine("Rows returned : " + dt.Rows.Count);
foreach(DataRow dr in dt.Rows)
{
Console.WriteLine(dr["SomeResultingColumn"]);
}