0

i am using sqlite client for windows phone for my database. I run into an issue regarding text formatting in this code :

cmd.CommandText = @" Insert into Restaurants (address,description,id,latitude,longitude,name,opening_hours,phone,sandwich,price,updated_at,website,score,rating_count,thumbnail_url) values ('" + r.address + "','" + r.description + "',"+r.id +","+r.latitude+","+r.longitude+",'"+r.name+"','"+r.opening_hours+"','"+r.phone+"','"+r.sandwich+"','"+r.price+"','"+r.updated_at+"','"+r.website+"',"+r.score+","+r.rating_count+",'"+r.thumbnail_url+"')";
cmd.ExecuteScalar();

The issue is that the text fields maybe like "xyz it's abc" and so the ' breaks my update command. How can i keep the ' and make my code run?

2

4 Answers 4

3

Use Parameter instead of hard coded string (query).

cmd.CommandText = @"Insert into Restaurants 
    (address,description,id,latitude,longitude,name,opening_hours,
      phone,sandwich,price,updated_at,website,score,rating_count,thumbnail_url) 
  values 
    (@address,@description,@id,@latitude,@longitude,@name,@opening_hours,
      @phone,@sandwich,@price,@updated_at,@website,@score,
        @rating_count,@thumbnail_url)";
Sign up to request clarification or add additional context in comments.

Comments

3

Instead of using a verbatim query string, which is (more) open to attack, use parameters instead:

cmd.Parameters.Add("@Param0", SqlDbType.VarChar, 80).Value = "value";

2 Comments

don't have Parameters, this sqlite implementation isn't an official one(windows phone doesn't support sqlite native)
@BadescuAlexandru Then AVD's answer is probably your alternative to this solution - you might still need some manual escaping however, to execute successfully.
0

Consider using stored procedures or parameterised queries rather than direct SQL. This will have the added benefit of making your code less susceptible to issues.

Comments

0

You could escape the characters by doing something like:

cmd.CommandText = cmd.CommandText.Replace("'", "''");

But building a query the way you do could lead to some serious security risks. Have a look at the following article which describes how to change dynamic sql to use sql parameters:

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.