0

I have a textbox in my WinForm.

The user types text (anything that their keyboard allows). When they click save, sometimes an error message appears with

Syntax Error (missing operator) in query expression

I know that certain characters like ' are breaking my SQL query

I have a few questions

  1. Is there anything I can do so that my Query doesn't break and allow users to type whatever they want?
  2. If there isnt a way to do #1, how can I scan the text and remove all characters that would break my Query?
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177

3 Answers3

5

try passing the textbox value to the query by using parameters. This will also prevent SQL-injection attacks.

should look something like this:

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * from TableName WHERE FieldA = @FieldValue";
cmd.CommandType = CommandType.Text;

//Define SqlParameter object and assign value to the parameter
cmd.Parameters.Add("@FieldValue", SqlDbType.VarChar, 50);
cmd.Parameters["@FieldValue"].Value = TextBox.Value;
amaters
  • 2,266
  • 2
  • 24
  • 44
2

I know that certain characters like ' are breaking my SQL query

It sounds like your using string concatenation to add your parameters if this is case.

Use SQL Parameters instead and this should solve your problem.

Also its worth noting, building SQL queries with string concatenation is prone to SQL Injection.

Curtis
  • 101,612
  • 66
  • 270
  • 352
0
  1. A better way is to use parametrized queries. See Adding Parameters to Commands. This does not only solve your bad character problem but also removes the danger of SQL-injection (Wikipedia).

  2. If you still prefer to use string concatenation then replacing single quotes by two single quotes should be safe enough.

string sql = "SELECT * FROM tbl WHERE Name = '" + name.Replace("'","''") + "'";
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188