Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an integer value from SQL Server

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?

like image 465
Eren Hatırnaz Avatar asked Jul 04 '26 00:07

Eren Hatırnaz


1 Answers

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'"
like image 57
Dylan Smith Avatar answered Jul 06 '26 18:07

Dylan Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!