Macpp
Macpp

Reputation: 33

Read a specific row from database using a variable

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

Answers (2)

Il Vic
Il Vic

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

Andrey
Andrey

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

Related Questions