ExecuteReader() question

  • I am new to SQL and C# programming and I am trying to create a query using the following string command:

    // build the query

    string strCommandText = "SELECT CopierTranslator.CopierModel, CopierTranslator.ProductIdentification FROM CopierTranslator";

    // add the filter

    string filterValue = CopierTransTextBox1.Text;

    strCommandText += " WHERE CopierTranslator.CopierModel = " + filterValue;

    // add the ordering

    strCommandText += " ORDER BY CopierTranslator.ProductIdentification";

    // create the command

    SqlCommand myCommand = new SqlCommand(strCommandText, myConnection);

    // open the database connection

    myConnection.Open();

    // show the data

    GridView1.DataSource = myCommand.ExecuteReader();

    GridView1.DataBind();

    Where filterValue is the value entered in a text box. The strCommandText builds out to look like this:

    "SELECT CopierTranslator.CopierModel, CopierTranslator.ProductIdentification FROM CopierTranslator WHERE CopierTranslator.CopierModel = MX-C311 ORDER BY CopierTranslator.ProductIdentification"

    My problem is when the ExecuteReader is run it views the MX-C311 value entered by the user not as a data entry in my db but a column name. If I put " " around the MX-C311 value then ExecuteReader works correctly. Wondering if anyone can provide a suggestion as to how to handle this issue?

    Thanks for any assistance.

  • Beware! You are opening yourself up to SQL injection.

    See this article

  • You may find this article interesting.

    Regards,

    Willem
    http://wschampheleer.wordpress.com[/url]

  • stewartc-708166 (2/12/2010)


    Of course, the better choice would be to have the select in a stored proc, and to pass the text box value as a parameter.

    Absolutely Stewart, stored procedures are a far better way to do this.

    We don't know, however, what the OP's doing with this code, whether it's going into a production system or, as I suspect, he's just playing around. Whatever, I thought it would be good to show him the error of his ways early on. 🙂

  • I agree. The article I referred to contains plenty of examples at the end about when (not) to use dynamic sql.

    Regards,

    Willem
    http://wschampheleer.wordpress.com[/url]

  • wschampheleer (2/12/2010)


    You may find this article interesting.

    Yes, thanks Willem, that's the other article I was looking for and couldn't find it. (Now bookmarked)

  • Just wating now for the OP to get back to us and say thanks a lot guys I'm glad you pointed this out to me. ;-).

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply