Reputation: 33
I have troubles reading an specific row from database.
I have an integer ni
and I want to read only this ni
row from the SQL Server database (if ni = 3 I need to read the third row).
private void intrebarea(int ni)
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl", con);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
}
I thought it is possible to use
SqlCommand cmd = new SqlCommand("Select * from tbl WHERE id=ni", con);
but obviously it doesn't work.
Any ideas, please?
Upvotes: 1
Views: 1719
Reputation: 5666
The best approach is to use parameters: your query will be faster and it will avoid SQL injection.
Take a look:
private void intrebarea(int ni)
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl Where Id = @Id", con);
cmd.Parameters.Add(new SqlParameter("@Id", System.Data.SqlDbType.Int)));
cmd.Parameters["@Id"].Value = ni;
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
}
Upvotes: 3
Reputation: 160
If I understand you right you should use:
SqlCommand cmd = new SqlCommand(string.Format("Select * from tbl where id={0}", ni), con);
Upvotes: 0