1

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?

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I needed. Thak you!
0

If I understand you right you should use:

SqlCommand cmd = new SqlCommand(string.Format("Select * from tbl where id={0}", ni), con);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.