I am trying to query a database in WebMatrix, something I've done several times, only this time, I have found some fields in the vendors column contain ampersands. I have looked over several articles, but none attack this solution from a WebMatrix point of view (actually, none really solve the direct issue, at all, and are instead work arounds for that specific environment).
I have also tried several things including C#'s Replace method (although, I was never able to get a clear example of what I should replace the ampersand with, if anything exists as a suitable replacement, that is), and escaping the ampersand with a backslash (clearly this didn't work).
What would be ideal would be an escape character in the sql environment itself, but, afaik, no such escape character exists. What should I replace the following query with to return rows whose fields contain ampersands, like so:
SELECT vendor_id FROM vendors WHERE vendor_name = 'J & H Equipment'
The above query returns no rows even though the vendor_name column contains a value (string) that is exactly 'J & H Equipment'
It bares mentioning that I am parameterizing my queries, so the actual query looks like:
string selectQueryString = "SELECT ap_vendor_id FROM ap_vendors WHERE ap_vendor_name = #0";
var code = db.QueryValue(selectQueryString, searchString);
After this code, I simply write the value to the page (with razor, and yes I have tried Html.Raw(code) and #code), because this is an AJAX call.
Also, Below is the replace function I have tried running before the actual query:
searchString = searchString.Replace("&", "\\&");
Note that the double backslashes are necessary as the '\' character is an escape character in C#, so two '\' equates to one '\' in C#.
--------------------------MY SOLUTION---------------------------
For me the solution was to use encodeURIComponent in my javascript before the AJAX call (I'm sure it is clear, by now, that I haven't been using AJAX for long).
The solution is to use encodeURIComponent in the javascript before the AJAX call.
Related
I'm working with matching an entire string within single quotes. The problem is, these strings are dynamically generated and I need to ignore all other single quotes within the first set of quotes. I've come across other solutions that are similar but I can't seem to tweak them to my needs.
Here is what I've worked with so far:
'(?:''|[^'])*'
I would like to match essentially everything within the first and last single quotes between content: and ;
Some example text:
#bottom {
content: 'Here we have an embedded unescaped 'single' that is generated at runtime. {Let's ignore it
please'
;
}
This is the playground I've been working in:
https://regex101.com/r/ITHciu/2
Any help would be greatly appreciated.
If you absolutely have to use Regexes for this and you are certain that ; will not be inside the string you are searching for, you could try this: '[^;]*'\s*;$. It will select everything from a ' and go until a like that ends with whitesapce and a ;.
Edit: if you need the stuff between the ' and ';, you could use a group '([^;]*)'\s*;$.
However, a much cleaner solution would be to make a little parser, that will read the string char by char. It's a fun exercise if you got a little bit more time.
If nothing else, you could use that regex to correct the invalid syntax in your files. And tell the people manually writing them what the valid syntax should be.
This might seem like a question that's been answered many times. My team and I have tried many solutions over the past hour without any luck. We have a database driven string value that contains c:\test and we want to replace the backslash with \\ resulting in c:\\test.
We've tried using .Replace, Regex.Replace, .Split and rebuilding the string, I tried using a for loop and substring to examine each character. When you get past the colon the next character shows up as "\t".
Please try the solution before submitting as we've tried a lot of different methods including dozens of suggestions already on stack overflow.
If we manually set the string as a literal like path = #"c:\test" then using replace works fine.
I would think that the solution would be to create a string that doesn't process the escape character but I have no idea how to implement that.
Sounds like your string already contains "tab" character ('\t') you probably need to replace it with "\\t" :
var result = "c:\test".Replace("\t", "\\t");
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.
How do i escape "%" character in a dynamic MDX. I want "%" to be treated as a literal and not a wild card in MDX.
Here is a basic idea of what is happening :
I have a windows form (using c#) where user can create a dynamic search expression for MDX query.
E.g.
Currency Contains US
where "Currency" is static, condition "Contains" is a dropdown selectable value and then a textbox for "US".
So user clicks "Search" and a dynamic MDX is formed with above condition and a cube hit occurs.
Now, i dont get correct result when query is like :
Calculation Contains 50%
Here, % is treated as wild card and anything containing "50" is shown.
Please Help. I have tried quotes "", square brackets [], back slash \, double characters %%. but no luck.
UPDATE :
Its actually the front end meaning for the user, at the back end i use Analysis Stored Procedures, "IsLike" for this. Query is something like this : { WITH MEMBER [Measures].[Search] AS IIF( [ASSP].[IsLike] ([Calculation].[Calculation].CurrentMember.Properties('MEMBER_CAPTION'),'%50%%')}
Thanks
If I understand your question correctly, then you are using the ASSP (Analysis Stored Procedures) IsLike method, and want to know how you can escape a % in the like template so that it is searched for literally. Looking at the source code (http://asstoredprocedures.codeplex.com/SourceControl/latest#ASSP/StringFilters.cs, method LikeToRegEx), I do not see an easy way to achieve this. In this method, a percent is replaced unconditionally by ".*". What you could do is download the ASSP source code and change this method to allow escaping the percent e. g. with "[%]" which would work in the SQL Server relational engine like.
E. g. you could add after the
sb.Replace("[.]", #"_");
another line
sb.Replace("[\.]", #"%");
which would revert the overly aggressive replace of [%] with [.*].
Then you would compile this and re-deploy.