How to replace apostrophe with double apostrophe in string? - c#

I have a string
good overview of ESP's in more detail than you probably need.
While inserting into SQL table it is giving error. So I want replace apostrophe in the string with double apostrophe like
good overview of ESP''s in more detail than you probably need
How to manipulate this in c#?

Very easy:
string s = "good overview of ESP's in more detail than you probably need.";
string escaped = s.Replace("'","''");
Note: It is usually safer to use command parameters. Especially if the values of the input strings are not controlled by your code (i.e. user entries).

Use the Parameter object.
myCommand.InsertCommand.Parameters.Add("#myString", SqlDbType.VarChar, 200);
myCommand.InsertCommand.Parameters["#myString"].Value = #"good overview of ESP's in more detail than you probably need.";

I was working on this problem for ages. Do it on the client, replacing the single quote with two single quotes. This works if you are executing an sp with several varchar input parameters. The only problem with this is SQL injection i.e. people can see what you are up to on the client which is never a good thing. The only way round this is to use SQLparameters on the server, as they have said earlier.

String.Replace(String,String) should work fine. In this example, you'd want:
String.Replace("'", "''")
However, I don't think that that'll fix your issue. I imagine you're more appropriately looking for:
String.Replace("'", "\'")
The reason for this being that MySQL, and I'd imagine other versions of SQL, expect strings to be enclosed in single quotes.

myCommand.InsertCommand.Parameters.Add("#myString", SqlDbType.VarChar, 200);
myCommand.InsertCommand.Parameters["#myString"].Value

Related

Automatically escaping characters within strings

I am working on a C# project where I am exporting data from a database that is defined by the user so I have no idea what the data is going to contain or the format it is going to be in.
Some of the strings within the database might include apostrophe's (') which I need to escape but everything I've found on the internet shows that I would have to do string.replace("'", "\'"); which seems a bit odd as it would be a mass of replace statements for every possibility.
Isn't there a better way to do this.
Thanks for any help you can provide.
I recently had to make a code fix for this same problem. I had to put a ton of string.replace() statements everywhere. My recommendation would be to create a method that handles all escape character possibilities and have your query strings pass through this method before being executed. If you design your structure correctly you should only have to call this method once.
public string FixEscapeCharacterSequence(string query)
{
query = query.Replace("'", "\'");
//..Any other replace statements you need
//....
return query;
}

Replace all single quotes with two single quotes in a string

I am trying to read value from DB using c#.
The query string contains multiple single quotes - such as: Esca'pes' (the query strings are being read from a text file)
So, I wanted to replace all the single quotes with two single quotes before forming the SQL query. My code is as below:
if (name.Contains('\''))
{
name = name.Replace('\'','\''');
}
How to fix this?
Use strings, not char literals.
name = name.Replace("'", "''");
However it sounds like you're concatenating SQL strings together. This is a huge "DO NOT" rule in modern application design because of the risk of SQL injection. Please use SQL parameters instead. Every modern DBMS platform supports them, including ADO.NET with SQL Server and MySQL, even Access supports them.
name = name.Replace("'","''");
On an unrelated note, you're concatenating strings for use in SQL? Try parameters instead, that's what they're meant for. You're probably making it harder than it needs to be.
Since you want to replace a single character with two characters, you need to use the String overload of Replace
if (name.Contains('\''))
{
name = name.Replace("'","''");
}
(Note: single quotes don't require escaping in Strings like they do in character notation.)

How to avoid double quote escape in C# strings?

In Ruby it's possible to use the strings without the need to escape the double quote in the string, like Q/Some my string with "double quotes"/
Is it possible with C# to use a string without a need to escape double quotes?
For a good reason I need to write inline SQL and it's very annoying to escape double quotes every time I put SQL query from DB console to C# code.
I know it's possible to use \" or "" as one double quote. But is it possible to avoid the need to escape the double quotes?
No, basically. You have the choice of "foo \" bar" or #"foo "" bar", both of which you have mentioned. However, frankly I rarely find " necessary in SQL; you have ' for literal strings and [ / ] for object/column names - of course, this might just be because I usually use SQL Server.
The only alternative that doesn't involve any escaping is to move the SQL to an external resource file, maybe a text file. That, though, is probably more painful than just using "".
No, this is not possible in C#. You could write your SQL in a separate file and then read it from there.
For a good reason I need to write inline SQL and it's very annoying to
escape double quotes every time I put SQL query from DB console to C#
code.
If you are writing a Inline Sql Query you don't need to worry about quotes if you passed the values via SqlParameters. This way you won't see the annoying double quotes every where and even your query will safe from Sql Injection

Replacing backslash in a string

I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

mysql is not accepting decimal in the right format

When I am sending decimal value from C# for example : 5.54
When I am executing query I can see that my variables are represented as 5,54
Anyone have an idea how to achieve to get DOT and not COMMA?
Here is my code:
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
Anyone have an idea how to achieve to get DOT and not COMMA?
Don't embed the values into your SQL directly to start with. Use parameterized SQL instead. See the documentation for MySqlCommand.Parameters for an example. You should always use parameterized queries:
They separate code from data
They prevent SQL injection attacks (not an issue for these numbers, but consider strings...)
They prevent conversion issues like this
There's a more general point here: don't perform any more conversions than you have to. Every time you convert data from one form to another, you risk losing data or worse. If you can keep your data in the most appropriate representation for as long as possible, you'll minimize the problems.
I totally agree with the other advice. As to the other question regarding comma or dot, it depends on the CurrentCulture. To get the right format you would have to use a ToString, providing Culture.InvariantCulture as the second parameter. This will use the dot for decimal separator.
But, I insist, the other answer is very good advice: use DbParameters. And I add: pass the value as held in C#, not converting it to string. It will be correctly handled by the ADO.NET provider. I.e. if you have to pass a float variable, do pass it without converting to string, but as is, as a float value.

Categories