Fetching MAX id from SQL Server database causes exception - c#

I am fetching maximum ID from table PatientInfo using this code:
private void LoadID()
{
string query = "SELECT MAX(ID) FROM PatientInfo";
using (SqlConnection cn = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
txtid.Text = reader["ID"].ToString();
}
}
else
{
// other code
}
reader.Close();
cn.Close();
}
}
Because I have to first check whether any record exist or not, I'm using reader.HasRows. After that the code should get the ID and put it to the textbox. But it's not. It's throwing an IndexOutOfRangeException. I can't figure it out why.
In my database I have one record inserted. But its still giving the same result in both the conditions (1. when I have no data in table and 2. When I have data in table)
Secondly, I am trying to manually enter data in the table but it is doing nothing and saying the following thing
and hence, no data is added

ID is not a field in your query, you have to alias your MAX
string query = "SELECT MAX(ID) AS ID FROM PatientInfo";

Related

Displaying Selected values(Sql query) using c# and html

I want to display the data that is selected in the SQL query , I tried to use ExecuteScalar() but it only work with 1 value , here is my c# code :
SqlConnection conn = new SqlConnection("Data Source=MAX-PC\\SQLEXPRESS;Initial Catalog=newSchool;Integrated Security=True");
SqlCommand cmd = new SqlCommand("view_profile", conn);
cmd.CommandText = "exec view_profile #posted_id";
cmd.Parameters.AddWithValue("#posted_id", WebForm1.x);
conn.Open();
cmd.ExecuteNonQuery;
conn.Close();
and that's the proc :
CREATE PROC view_profile
#posted_in INTEGER
AS
BEGIN
SELECT P.poster , P.post_description
FROM Posts P
WHERE P.posted_in = #posted_in
END
you are a little confused:
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.
ExecuteNonQuery(): Executes a Transact-SQL statement against the connection and returns the number of rows affected, it is intended for UPDATE, INSERT and DELETE queries
What you need is ExecuteReader()
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}

How do i check database table through datatable and extract information of another column of database table?

I was trying to check whether there is any rows having username and friend username in database table. If any then I have to take the friendship status in a string and will return that string.
Here is the code:
string query = "Select * from tblfriend where username = '" + username + "'and friend = '" + friendname + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
rows = dt.Rows.Count;
if (rows > 0)
{
friendship = reader["friendshipstatus"].ToString();
}
But it gives a error message:
Invalid Call to call MetaData when reader is closed.
Can you guys please give a hint?
Since you are loading DataTable from same reader it may be closed after the loading complete.
As Side node, you better use parameters, using statements etc like below
string queryString = "Select [friendshipstatus] from [tblfriend] where [username] = #username and [friend] = #friend";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#friend", friendname );
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if(reader.Read()) // you have matching record if this condition true
{
friendship = reader.GetString(0); // get the value of friendshipstatus
}
}
}
You're using the reader to populate data table and then when it had already been used for that - attempt to use it again.
There are better ways to retrieve single value from db (look up ExecuteScalar) but to make your current code work replace the last line with
friendship = dt.rows[0].["friendshipstatus"].ToString()
This will get the data from the data table you populated instead of closed reader.
You should use dataadapter if you want to read data into table
DataTable dt = new DataTable();
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(query, con))
{
// Use DataAdapter to fill DataTable
a.Fill(dt);
// read data here
}
rows = dt.Rows.Count;
if (rows > 0)
{
friendship = dt.Rows[0]["friendshipstatus"].ToString();
}

SQL Data Reader: Invalid attempt to read when no data is present

I am trying to use a SqlDataReader to run a query and then display the results in a messagebox, but I keep getting the error
Invalid attempt to read when no data is present.
Here is my code.
public void button1_Click(object sender, EventArgs e)
{
string results = "";
using (SqlConnection cs = new SqlConnection(#"Server=100-nurex-x-001.acds.net;Database=Report;User Id=reports;Password=mypassword"))
{
cs.Open();
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
//MessageBox.Show(dr.GetValue(0).ToString());
//MessageBox.Show(results);
}
MessageBox.Show(results);
}
}
}
}
That's correct.
When you exit from the while loop the DataReader has reached the end of the loaded data and thus cannot be used to get the value of a non-existant current record.
The Read method advances the SqlDataReader (dr) to the next record and it returns true if there are more rows, otherwise false.
If you have only one record you could use the results variable in this way
MessageBox.Show(results);
Now, this will work because you have a TOP 1 in your sql statement, but, if you have more than one record, it will show only the value of the last record.
Also as noted by marc_s in its comment, if your table is empty, your code doesn't fall inside the while loop, so probably you could initialize the results variable with a message like:
results = "No data found";
EDIT: Seeing your comment below then you should change your code in this way
.....
// Use parameters **ALWAYS** -- **NEVER** cancatenate/substitute strings
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
}
}
}
.....
I ran into a similar issue trying to get a GUID I knew was there - I could run the same SQL directly in SQL Management Studio and get my result. So instead of trying to bring it back as a GUID (it was saved in a char(35) field, even though it really was a GUID!), I brought it back as a string, instead:
SqlConnection sqlConn = null;
string projId = String.Empty;
string queryString = "SELECT * FROM project WHERE project_name='My Project'";
try
{
sqlConn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString, sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
projId = reader.GetSqlValue(0).ToString(); // <-- safest way I found to get the first column's parameter -- increment the index if it is another column in your result
}
}
reader.Close();
sqlConn.Close();
return projId;
}
catch (SqlException ex)
{
// handle error
return projId;
}
catch (Exception ex)
{
// handle error
return projId;
}
finally
{
sqlConn.Close();
}

Get int value from command in c#

string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0
but I want to get the id of user?
how can I get it?
You need the SqlDataReader.
SqlDataReader Provides a way of reading a forward-only stream of rows from a SQL Server database.
Sample
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) {
rd.Read(); // read first row
var userId = rd.GetInt32(0);
}
More Information
MSDN - SqlDataReader Class
Simply cast the returned value:
int userId = (Int32)cmd.ExecuteScalar();
But be aware that ExecuteScalar will return null if your query returns an empty result set, and in that case the above code snippet will throw an InvalidCastException.
try with select TOP 1 and ExecuteScalar
string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
var result = (Int32)cmd.ExecuteScalar();
}
}

Simple SQL select in C#?

On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
Is there an easier way to make a simple select query? In php, I can just use mysql_query and then mysql_result and I'm done.
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
Thanks for any tips.
You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You are probably looking for SqlCommand and SqlDataReader
Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
string query = "SELECT UserId, UserName FROM Users";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
users.Add(reader.GetInt32(0), reader.GetString(1));
}
connection.Close();
}
Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.
.NET Framework Class Library
SqlCommand..::.ExecuteScalar Method
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.
You can do something very similar:
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
conn.Open();
return cmd.ExecuteScalar();
}
you can use SqlCommands executeScalar function. Please look at the following link
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Categories

Resources