I am trying to store the results of a MySql query into a variable so that I can output the result as part of a sentence.
The query is as follows:
MySqlCommand command = conn.CreateCommand();
command.CommandText = "select count(*) from customerdetails";
conn.Open();
command.ExecuteNonQuery();
I have read other forums and they have spoken about a method using "addwithvalue" however this hasnt been successful when I have used it, and the query result hasn't been outputted.
ExecuteNonQuery()
is used for doing any insert, updates or delete operations only.
ExecuteNonQuery :
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
For selecting data you need to use ExecuteReader()
which will read the data from the table in a sequential way.
ExecuteReader :
Sends the CommandText to the Connection and builds a SqlDataReader .
So you will have to write it like:
MySqlDataReader reader = command.ExecuteReader();
int rowsCount = 0;
if(reader.Read())
{
rowsCount = reader.GetInt32(0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.