2

This code is written in C# and it is calling database to get the data from it. But I don't understand what does "WHERE b.CompRec = ?" mean

    public string GetFileNameAndTitle(int compRec)
    {
        string fileNameAndTitle = "";
        string sql = "SELECT a.FileName, a.Title FROM (Files a INNER JOIN Components b ON a.RecNo=b.FileRec) WHERE b.CompRec = ?";
        using (OleDbCommand cmd = new OleDbCommand(sql, cn))
        {               
            cmd.Parameters.AddWithValue("@CompRec", compRec);
            OpenConnection();    }
2

2 Answers 2

10

It is a parameterized statement.

cmd.Parameters.AddWithValue("@CompRec", compRec);

That line sets the actual value when the query is executed at the server. This prevents SQL Injection and is the 100% right approach!

4
  • The 100% right can be to create a SP and just call the SP instead off using dynamic SQL (that helps the engine) and to type the parameters to tell the DB what he is geting.
    – jean
    Dec 5, 2013 at 19:20
  • 1
    @jean, that's quite arguable. The statement's execution plan would get cached the first time through, and subsequent calls would use the same plan because it's parameterized. Dec 5, 2013 at 19:20
  • 2
    @jean AddWithValue infers the type. It's only if this inferrence is wrong or could be more precise that you'd benefit from explicitly typing them via SP or something else.
    – Tim S.
    Dec 5, 2013 at 19:24
  • 1
    Great answer Michael, +1.
    – Brian
    Dec 5, 2013 at 19:59
2

It's basically a placeholder where you will put data later. This lets you split up your SQL statement from the data used in the query. This is the syntax of parameterized statements.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.