I'm trying to find the count for a table using C# SqlDataReader but I keep getting
invalid attempt to read when no data is present
My code:
string sql = "SELECT COUNT(*) FROM [DB].[dbo].[myTable]";
SqlCommand cmd = new SqlComman(sql, connectionString);
SqlDataReader mySqlDataReader = cmd.ExecuteReader();
int count = mySqlDataReader.GetInt32(0); // Here is where I get the error.
I know I have a valid connection to the database because I can read and write to it in many places, what's special about the COUNT(*) that I cannot read it properly? How do I get the int count to be populated?
You have to read it:
if (mySqlDataReader.Read()) {
count = mySqlDataReader.GetInt32(0);
}
Alternatively, you can just use ExecuteScalar:
int count = (int)cmd.ExecuteScalar();
which is defined as:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
ExecuteScalar is what you require.
Related
I have a SQL query which supposed to return only ONE row from the business database. Based on this, I have written following sql script to get the data from the result set.
string query = #"select
ProdMaster.data_Id Id,
ProdMaster.data_name Name,
ProdMaster.data_countryname CountryName
from RM.Db
order by ProdMaster.data.FromDate desc"
SqlCommand command = new SqlCommand(query, conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
countryname = reader["CountryName"].ToString();
}
}
But, there is some data issue in the database, sometimes it returns multiple rows.
How do we check the row count? If rows more than one we want to return a custom exception.
Note:
I do not want to use COUNT(*) in the query.
We don't have control on RM.Db database - it might have data issues (3rd party)
Don't you consider the next approach to solve your problem:
SqlCommand command = new SqlCommand(query, conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
countryname = reader["CountryName"].ToString();
}
// Try to read the second row.
if (reader.Read())
{
// If we are inside this if-statement then it means that the query has returned more than one row.
// Here a custom exception must be thrown.
}
}
You can use SqlDataAdapter instead and fill the contents from the table in a dataset. The dataset will have a table inside it you can count the row like this - ds.Tables[0].Rows.Count
There can be problems related to Datareader as it is a stream of data and db can have changes while reading. A more thorough discussion on the same can be found on this thread -
How to get number of rows using SqlDataReader in C#
I'm trying to get the last row of a table using C# but it doesn't seem to be working, this is my code:
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
The value this returns is -1 while it should be returning 59.
The strange thing is is that when I run this command in phpmyadmin I DO get 59.
Any ideas on why C# is not returning the correct value but phpmyadmin is?
EDIT: problem solved, should've uses ExecuteScalar(). Looks like I've been staring at my monitor for a bit too long...
You need to use ExecuteScalar instead of ExecuteNonQuery.
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteScalar().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
This should resolve your issue.
The value this returns is -1 while it should be returning 59.
No, it's behaving exactly as documented by IDbCommand.ExecuteNonQuery:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.
You're using a SELECT statement - a query. So instead of executing ExecuteNonQuery, you should be using ExecuteQuery and iterating over the results, or ExecuteScalar, given that you know you'll have a single result:
string contactID = cmdGetID.ExecuteScalar().ToString();
you should use ExecuteScalar because you are returning value ExecuteNonQuery returns the number of rows affected by update delete or insert opeation
you can check this for more info
ExecuteNonQuery
Returns the number of rows affected.
ExecuteScalar
Executes the query, and returns the first column of the first row in
the result set returned by the query. Additional columns or rows are
ignored.
for more information you can check this The MySqlCommand Object
you can use query like this
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT TOP 1 ContactID FROM Contacten ORDER BY ContactID";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
I am trying to run the SQL Select query in my C# code. But I always get the -1 output on
int result = command.ExecuteNonQuery();
However, the same table if I use for delete or insert works...
ConnectString is also fine.
Please check below code
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=#zip", conn);
//command.Parameters.AddWithValue("#zip","india");
int result = command.ExecuteNonQuery();
// result gives the -1 output.. but on insert its 1
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
conn.Close();
The query works fine on SQL Server, but I am not getting why only select query is not working.
All other queries are working.
SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
SqlCommand.ExecuteScalar Method
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
So to get no. of statements returned by SELECT statement you have to use ExecuteScalar method.
Reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
So try below code:
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=#zip", conn);
command.Parameters.AddWithValue("#zip","india");
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
}
}
conn.Close();
According to MSDN
http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.
If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():
int result = (int) (command.ExecuteScalar());
However, if you expect many rows to be returned, ExecuteReader() is the only option:
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
int result = reader.GetInt32(0);
...
}
}
you can use ExecuteScalar() in place of ExecuteNonQuery() to get a single result
use it like this
Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));
It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
As you want only one row in return, remove this use of SqlDataReader from your code
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
because it will again execute your command and effect your page performance.
That is by design.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
you have to add parameter also #zip
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=#zip", conn);
//
// Add new SqlParameter to the command.
//
command.Parameters.AddWithValue("#zip","india");
int result = (Int32) (command.ExecuteScalar());
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
conn.Close();
You should use ExecuteScalar() (which returns the first row first column) instead of ExecuteNonQuery() (which returns the no. of rows affected).
You should refer differences between executescalar and executenonquery for more details.
Hope it helps!
I have an SQL query as follows:
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName=about",conn);
//cmd.Parameters.Add("#pageName","hakkinda");
SqlDataReader reader = cmd.ExecuteReader();
flID = reader.GetInt16(0);
reader.Close();
conn.Close();
I get an error message:
Invalid attempt to read when no data is present.
What's wrong?
I notice a couple potential issues:
You need to call reader.Read(), before trying to read data from it. This is usually done in a loop when people expect multiple rows.
while (reader.Read()) {
flID = reader.GetInt16(0);
}
also in your SQL if "about" is meant to be a literal and not another column name you probably need single quotes around it:
"SELECT id FROM Pages WHERE pageName='about'"
Your query is returning 0 results. This is because the parameter value in the SQL string is missing quotes. It should read as follows (notice the single quotes around the word 'about'):
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about'",conn);
You have to call DataReader.Read to fetch the result:
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
while (reader.Read()) {
// read data here
}
Your select statement should be:
"SELECT id FROM Pages WHERE pageName='about'"
If you expect only single value to be returned, you can use .ExecuteScalar()
flID = int.Parse(query.ExecuteScalar().ToString());
Also, use single quotation marks for pageName value.
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about';",conn);
I would like to know how can I get record count of a query with C#.
Here is the code that I use..
MySqlDataReader recordset = null;
query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
recordset = query.ExecuteReader();
while (recordset.Read())
{
result.Add(recordset["type_ID"].ToString());
}
return result;
I was using a SELECT COUNT(*) and expected an int to be returned. You may need this to get a usable value:
mysqlint = int.Parse(query.ExecuteScalar().ToString());
A couple of things...
The SQL statement you would use is:
SELECT COUNT(*) FROM test
However, when using the MySQL Connector/Net to connect to MySQL through C# there is some care to be given when handling query results.
For example, as cited in this question and on Microsoft Connect int.Parse("0") equivalently known as Int32.Parse("0") can throw a FormatException on some machines.
I have found that Convert.ToInt32 handles this case nicely.
So your code will be something like this:
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM test", conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
return count;
}
}
Remember to make use of using statements in order to ensure that the MySQL objects get disposed of properly.
You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.
You could run another query first to get the count :
query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);
but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.