0

I have written the following script (in c#):

string     sqlCommand = "SELECT   * " +
                 "FROM     tblMatches " +
                 "WHERE matchPlayerNick =" + comboBoxPlayer.Text + " " +
                 "ORDER BY matchName ";

When I run my program, I get this: "data type mismatch in the criteria experssion". the datatype of matchPlayer is, of course, "text".

what's wrong with the script then?

thanks!

3
  • 3
    a lot is quite wrong with this. Please google sql injection... But what you are looking for is the lack of single quotes surrounding your text field. Commented May 3, 2013 at 14:22
  • You should look into parameterized queries. Commented May 3, 2013 at 14:23
  • 1
    injection attack, injection attack, injection attack. If I type ; DELETE tblMatches; GO in the combo box, you may have issues. Commented May 3, 2013 at 14:24

2 Answers 2

4
string     sqlCommand = "SELECT   * " +
                 "FROM     tblMatches " +
                 "WHERE matchPlayerNick ='" + comboBoxPlayer.Text + "' " +
                 "ORDER BY matchName ";

but the query above is vulnerable with sql injection. It can be prevented if you parameterized the values using Command Object and Parameters.

Try this code snippet:

string content = comboBoxPlayer.Text;
string connStr = "connection string here";
string sqlCommand = @"SELECT   *
                      FROM     tblMatches 
                      WHERE matchPlayerNick = @content
                      ORDER BY matchName";
using (SqlConnection conn = new SqlConnection(connStr))
{
    using(SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.CommandType = CommandType.Text;

        comm.Parameters.AddWithValue("@content", content);

        try
        {
            conn.Open();
            // other codes here
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

For proper coding

  • use using statement for propr object disposal
  • use try-catch block to properly handle objects
Sign up to request clarification or add additional context in comments.

1 Comment

@Idan you're welcome. Even if the value you are passing contains single quotes, it doesn't break the string.
4

You've forgotten the quotes. Using parameterized queries, it's a good practice.

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.