I am trying to migrate the database layer of our framework from SQLServer to MySQL using MySql.data.dll . I have the following generated query in MySQL:
select * from `user` where `user_domainname` = 'domain\beth';
MySQL is interpreting the '\b' in the above string as an bell character whereas SqlServer does not interpret any such escape characters. The solution for this in MySQL -
select * from `user` where `user_domainname` = 'domain\\beth';
To do this in C#, I would have to replace every \b or other such characters with \b which would not be a very feasible option for me considering the number of such transformations I would end up doing.
So my question is- Is there any option in MySQL to avoid it interpreting such special characters at the database level. If not what is there any api I can use to perform such a transformation. I did check out the MySqlHelper class but could not find anything useful there.
Thanks in advance,
Bharath
Starting with MySQL 5.0.1, you can set NO_BACKSLASH_ESCAPES to turn the backslash into yet another ordinary character. Be sure you never rely on a backslash somewhere else though!
To do this on a live server (until it reboots):
SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';
Don't forget to add it to your MySQL configuration file (my.cnf or my.ini) so it takes effect on the next startup! Add the line
sql-mode=NO_BACKSLASH_ESCAPE
Related
I am trying to read a dbf file through ADO using the FoxPro OLEDB driver. I can query fine however there are some special characters which do not seem to be coming through. They are not printable characters as disappear when clicked on however are definitely not the same via OLEDB as they are in FoxPro.
For example, the following field through Visual FoxPro:
When this is accessed through OLEDB it displays as the following:
I've narrowed this down to the fact that the first string contains the ASCII code 0 (null) character as the 10th character - this is valid however so I do not wish to remove it, but whatever I try the string ends after 9 characters when reading with ADO.
You don't show us any code and the image links are broken, we are left out with guesses. I have been using VFPOLEDB driver from C# for years and do no have this problem. I believe you are trying to describe a problem that exists on C# side and not VFP side. In VFP even the char(0) is a valid character. In C# however (docs are misleading IMO, says this is not the case but it is) strings are ASCIIZ strings where char(0) is accepted as the end of string. This should be your problem. You could simply read as a byte array instead, casting the field to a blob. Something like:
Instead of plain SQL like this:
select myField from myTable
Do like this and cast:
select cast(myField as w) as myField from myTable
EDIT: Images were not broken but blocked for me by my ISP, go figure why.
The MySQL documentation says that it should be \'. However, both scite and mysql shows that '' works. I saw that and it works. What should I do?
The MySQL documentation you cite actually says a little bit more than you mention. It also says,
A “'” inside a string quoted with “'” may be written as “''”.
(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)
I think the Postgres note on the backslash_quote (string) parameter is informative:
This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...
That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.
Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.
Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.
'He said, "Don''t!"'
What I believe user2087510 meant was:
name = 'something'
name = name.replace("'", "\\'")
I have also used this with success.
There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:
Use another single quote: 'I mustn''t sin!'
Use the escape character \ before the single quote': 'I mustn\'t sin!'
Use double quotes to enclose string instead of single quotes: "I mustn't sin!"
just write '' in place of ' i mean two times '
Here's an example:
SELECT * FROM pubs WHERE name LIKE "%John's%"
Just use double quotes to enclose the single quote.
If you insist in using single quotes (and the need to escape the character):
SELECT * FROM pubs WHERE name LIKE '%John\'s%'
Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too.
Here's an example of using prepared statements and bound parameters in PHP:
$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
return $dbh->errorInfo();
}
return "success";
In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to '. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.
Replace the string
value = value.replace(/'/g, "\\'");
where value is your string which is going to store in your Database.
Further,
NPM package for this, you can have look into it
https://www.npmjs.com/package/mysql-apostrophe
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.
see https://www.php.net/manual/en/mysqli.real-escape-string.php
Ok. Will try to explain with images... This is my SQL Server and my query:
As you see I getting the result. But then I start my app in VS2013, put break point when I want to call my stored procedure and copy text from VS:
And paste Name in Qhuery:
But I didn't get the result! The names ABSOLUTELY THE SAME!
This Query doesnt't work:
SELECT TOP 1 [Employee].[EmployeeID]
FROM [Employee]
WHERE [Employee].[FullName] = 'Brad Oelmann'
I agree the initial suspect is a "special character" that shows up as whitespace pasting in SSMS.
It has happened to me filtering client data with t-sql.
To replace special characters, there is a good starting point here:
.NET replace non-printable ASCII with string representation of hex code
In that case, they're looking for "control characters" in particular and doing a fancy replacement, but the idea of finding the special characters RegEx is the same.
You can look at all kinds of special sets of characters here:
http://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx
But it might be easier to define what you do want if you are doing something specific like a name.
For example, you can replace anything that isn't an English letter (for one example) with a space:
str = System.Text.RegularExpressions.Regex.Replace( _
str, _
"[^a-zA-Z]", _
" ")
It's really stupid, but I got simple solution. Since my DB Table contains only ~50 records, I retyped all names and now it works. So the problem was not in VS but in SQL Server side.
If somebady will have similar problem, first of all try to update data in your table somehow. You can try to select all data, copy-paste in in notepad and put it back in SQL Server.
I'm inserting some text into a SQL Server database using some C#. I'm using System.Web.HttpUtility.HtmlEncode() to attempt to replace characters that aren't compatible with the charset of my db (set to default collation = SQL_Latin1_General_CP1_CI_AS), but it is not helping me with some "weird" characters.
For example, this dash character:
―
is different from the standard dash character. (-)
HtmlEncode() doesn't replace the first dash with an entity (I think it is "—") and it ends up as a "?" in my database.
What is the best way to clean / sanitize a text field before inserting into SQL Server?
I would rather not change my database configuration / collation.
I want to be able to identify problematic characters in a string saved in my sql server using LINQ to Entities.
Problematic characters are characters which had problem in the encoding process.
This is an example of a problematic string : "testing�stringáאç".
In the above example only the � character is considered as problematic.
So for example the following string isn't considered problematic:"testingstringáאç".
How can I check this Varchar and identify that there are problematic chars in it?
Notice that my preferred solution is to identify it via a LINQ to entities query , but other solutions are also welcome - for example: some store procedure maybe?
I tried to play with Regex and with "LIKE" statement but with no success...
Check out the Encoding class.
It has a DecoderFallback Property and a EncoderFallback Property that lets you detect and substitute bad characters found during decoding.
.Net and NVARCHAR both use Unicode, so there is nothing inherently "problematic" (at least not for BMP characters).
So you first have to define what "problematic" in meant to mean:
characters are not mapped in target codepages
Simply convert between encodings and check whether data is lost:
CONVERT(NVARCHAR, CONVERT(VARCHAR, #originalNVarchar)) = #originalNVarchar
Note that you can use SQL Server collations using the COLLATE clause rather than using the default database collation.
characters cannot be displayed due to the fonts used
This cannot be easily done in .Net
You can do something like this:
DECLARE #StringWithProblem NVARCHAR(20) = N'This is '+NCHAR(8)+N'roblematic';
DECLARE #ProblemChars NVARCHAR(4000) = N'%['+NCHAR(0)+NCHAR(1)+NCHAR(8)+']%'; --list all problematic characters here, wrapped in %[]%
SELECT PATINDEX(#ProblemChars, #StringWithProblem), #StringWithProblem;
That gives you the index of the first problematic character or 0 if none is found.