1

I'm trying to search for a customers "forename", "surname", and "customerid" to show into a combo box through the use of sql.

     string strSql = "SELECT customerID&\" \" & forename &\" \" & surname AS FullName, surname FROM customer WHERE [customerID]='" + txtCustomerID.Text +"'";

Though with this code I get a "data mismatch exception" which I'm assuming is because I'm using a string and searching for an int?

squillman
  • 13,363
  • 3
  • 41
  • 60
Bunion
  • 441
  • 2
  • 9
  • 23
  • 2
    **Never** use string concatenations to build SQL queries. This code is vulnerable to SQL injection. Always use parametrized queries to avoid meeting with [`boby-tables`](http://bobby-tables.com/). – Darin Dimitrov Jan 09 '13 at 16:51
  • [How do Parameterized queries help against SQL Injection](http://stackoverflow.com/questions/5468425/how-do-parameterized-queries-help-against-sql-injection) – Alex K. Jan 09 '13 at 16:52

2 Answers2

1

just change this: You dont need to use the '' because its an int

string strSql = @"SELECT customerID +'\' + forename + '\' + surname AS FullName, surname FROM customer WHERE [customerID]=" + txtCustomerID.Text;

But as other have told you this is not a good practice to use string concatenations to build SQL queries, and more if its with parameters or data that you get from the users.

Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
0

As everyone says; do not construct queries from text fields, use a parameterized query:

SqlCommand sqlQuery = new SqlCommand("SELECT customerID, forename + ' ' + surname AS FullName FROM customer WHERE customerID = @customerID", sqlConnection);
sqlQuery.Parameters.AddWithValue("@customerID", Int32.Parse(txtCustomerID.Text));

You might also want to do some error-checking on txtCustomerID.Text.

Dour High Arch
  • 21,513
  • 29
  • 75
  • 90