Here is the code,.
var query = "SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%' + '" + data + "' + '%'";
That is how the Like operator works.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
The "%" sign is used to define wildcards (missing letters)
WHERE title LIKE '%computer%' finds all strings with the word 'computer' anywhere in the string.
It's a combination of C# string concatenation and SQL string concatenation.
C# part:
string b = "B";
string x = "A" + b + "C";
//gives you "ABC"
SQL:
'A' + 'B' + 'C'
// gives you 'ABC'
Combined:
sql = "'A' + '" + b + "' + 'C'";
Results in C# string
sql = "'A' + 'B' + 'C'"
Which results in SQL in
'ABC'
In your case, it results in
ADANo LIKE '%mydata%'
while mydata is the contents of data. It uses the LIKE comparsion operator on the field ADANo, which returns all the records where data is contained in ADANo. The % characters are wildcards, which mean that any number of any character can be before or after data.
By the way, if data is coming from the user, this kind of code is vulnerable to SQL injection. It means, that a user can execute arbitrary SQL on the database by passing it as data with some tricks. To avoid this, use a parameterized query.
It indeed looks redundant to split the `'%' and 'data'.
If we use the new $ syntax we get this:
var query = $"SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%' + '{data}' + '%'";
Now suppose data is foobar.
This results in
var query = $"SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%' + 'foobar' + '%'";
Which in turn results in
SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%foobar%'
So you can rewrite your statement to:
var query = $"SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%{data}%'";
Or with your string concat syntax:
var query = "SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%" + data + "%'";
Do notice that this approach (in general, not before or after these changes) is vulnerable to SQL Injection.
For example, what's the query when data is "FOO'; DELETE FROM [dbo].[LDDAP-ADA_Header]; --"
So your end result then is
"SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%FOO'; DELETE FROM [dbo].[LDDAP-ADA_Header]; --%'"
Which will clear out your table.
That's a plain-text search with the LIKE operator.
LIKE uses escape sequences like % to signify "any number of any characters/numbers here".
Basically the SQL-equivalent of a regex-search/comparison.
SELECT * FROM dbo.[LDDAP-ADA_Header]
WHERE ADANo LIKE '%' + 'foo' + '%'";
However, this code contains two mistakes:
1. Not using parameters, so it's vulnerable to SQL-injection.
2. Not escaping characters inside the string, like %
More correctly, this would be:
var query = "SELECT * FROM [dbo].[LDDAP-ADA_Header] WHERE ADANo LIKE '%' + '" + data.Replace("'", "''") + "' + '%'";
assuming data cannot be NULL, which probably doesn't have to be that way.
But for this to actually work, you'd need to use ESCAPE in the like-clause (and concat all characters in the string with \).
e.g. "% of size" ==> "\%\ \o\f\ \s\i\z\e"
SELECT * FROM [dbo].[LDDAP-ADA_Header]
WHERE ADANo LIKE '%' + #data + '%' ESCAPE '\'
The problem is, "data" is most-likely a user input field.
The (possibly malicious) user can put into that textbox whatever he wants.
And if you don't do data.Replace("'", "''"), he/she/it can set "data" to
string data = "'; DROP DATABASE whatever; -- "
and then you will have a problem (e.g. if I put "master" in place of "whatever")
Warning
Don't put that string into your data variable, unless you want to miss your master database.
Related
Currently I am using this statement:
"SELECT categoryDB, number FROM " + dbName+ " WHERE titleDBColumn ='" + titleInput+ "'";
Which helps me find strings that are similar to titleInput (which is a variable coming from the outside).
However, the values in titleDBColumn are almost always shorter strings than those coming in through titleInput.
Example:
titleDBColumn: Streetcar
titleInput: TheStreetCarIOwn
Now it's obvious that I need to use the LIKE operator in the other direction to get the results I want but I cant get the format right. Any ideas?
Sorry if I'm unclear.
This worked for me:
"SELECT categoryDB, number FROM " + dbName + " WHERE '" +
titleInput + "' like '%' + titleDBColumn + '%'";
The resulting SQL must be
SELECT categoryDB, number
FROM tableName
WHERE 'input' LIKE '%' + titleDBColumn + '%'
The % wildcard means "any number of any characters". I.e, 'input' LIKE '%' + titleDBColumn + '%' means that the input text may contain characters before and after the column text.
Also, you should use command parameters, whenever possible. This is not possible for the table name you called dbName. If this name is defined in the code and is not a user input, then it is safe to concatenate it as you did. But otherwise take measures to prevent SQL-Injection.
string sql = "SELECT categoryDB, number FROM `" + dbName +
"` WHERE #input LIKE '%' + titleDBColumn + '%'";
using (var conn = new MySqlConnection(connStr)) {
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#input", titleInput);
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
...
}
}
I have 2 spots where I need to use SQLParameter to parse SQL. One works and one does not and I cannot figure out why the second one doesn't work.
The first one that works is the following:
SqlCommand getShopDbNameCommand = new SqlCommand("SELECT TOP 1 [mappeddbName] FROM [ECM].[dbo].[EcmShop]" +
"WHERE [LicencePassCode] = #licCode AND [iPadLocation] = #shopId", this.mainConnection);
getShopDbNameCommand.Parameters.Add(new SqlParameter("licCode", currUser.LicCode));
getShopDbNameCommand.Parameters.Add(new SqlParameter("shopId", currUser.ShopID));
That works. On top of that, the majority of the tutorials I've read all say that I do not have to have a # in front of the parameter name inside of the new SqlParameter, only inside of the command text itself do I need a # in front of the parameter name.
The second command I am trying to run is the following:
string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink]" +
"WHERE [objectname] LIKE %" + "#compareStringA"+ "% OR [objectname] LIKE %" + "#compareStringB" +"%";
SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
getAuthCommand.Parameters.Add(new SqlParameter("compareStringA", "ABRAUTH"));
getAuthCommand.Parameters.Add(new SqlParameter("compareStringB", "ABRSAUTH"));
This does not work and throws an invalid syntax error. Using breakpoints it still looks like the command is trying to pass the literal #compareString string to SQL and thats whats causing the issue. Ive seen other posts on SOF that say to use the literal parameter name when defining new SqlParameter objects (meaning include the #) but everywhere outside of SoF say otherwise.
Any reason why the second command would throw invalid syntax errors?
your LIKE statements must be inside single quotes
SELECT * FROM Customers WHERE City LIKE '%s%';
the majority of the tutorials I've read all say that I do not have to have a # in front of the parameter name inside of the new SqlParameter,
The C# code for SqlParameter does not care if you put a # in the front or not when adding it to the Parameters collection, it will put a # behind the scenes for you.
For your query that is not working the correct way to do it is you will actually have 3 strings you add together in sql, the two '%' and your parameter. I am also changing the way you add parameters to explicitly set the data type, it is better to do that with strings.
string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink]" +
"WHERE [objectname] LIKE ('%' + #compareStringA + '%') OR [objectname] LIKE ('%' + #compareStringB +'%')";
SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
getAuthCommand.Parameters.Add("#compareStringA", SqlDbType.VarChar, 20).Value = "ABRAUTH"; //I had to guess on your datatype, I just did varchar(20), change as appropriate.
getAuthCommand.Parameters.Add("#compareStringB", SqlDbType.VarChar, 20).Value = "ABRSAUTH";
Try this:
string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink] " +
"WHERE [objectname] LIKE " + "#compareStringA"+ " OR [objectname] LIKE " + "#compareStringB" +"";
SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
getAuthCommand.Parameters.Add(new SqlParameter("compareStringA", "%ABRAUTH%"));
getAuthCommand.Parameters.Add(new SqlParameter("compareStringB", "%ABRSAUTH%"));
This Oracle SQL query written in c# is giving me the following error : invalid character
qur = " select * from emp where name LIKE '%" + TextBox1.Text + "%'";
How can I solve this?
The problem is your query is very open to Sql Injection attacks. Since you are not using parametrized queries anything entered in TextBox1 can crush your query.
for example if I enter : ' char in Textbox your query will be select * from emp where name LIKE '%'%' and it will throw error. And apart from that it is vulnerability and you should not use such queries.
You can change query to :
SqlCommand cmd= new SqlCommand( " select * from emp where name LIKE #myParam");
cmd.Parameters.AddWithValue("#myParam", "%" + TextBox1.Text + "%");
you missed #
How do parameterized queries help against SQL injection?
C# constructing parameter query SQL - LIKE %
you should use it as below:
qur = " select * from emp where name LIKE '%'" + TextBox1.Text + "'%'";
I need to insert a string into an Sql Command
search.CommandText = "SELECT * FROM Contacts WHERE Name like ' + #person + % + '";
What it the right way of using LIKE in a command?
Should be:
SELECT * FROM Contacts WHERE Name like #person + '%'
#person is a parameter - you don't need single quotes around it. You only need to concatenate it with %, which should have quotes.
Keep in mind:
You could have kept it "SELECT * FROM Contacts WHERE Name like #person", and have the parameter value contain % (concatenate in C# is simpler to understand).
You may also want to escape other wildcard characters already in the string: %, _, [ and ].
Use Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
For Example:
LIKE '%xy' would get you anything ending with 'xy'
LIKE '%xy%' would get you anything contains the 'xy'
LIKE 'xy%' would get you anything starting with 'xy'
Is this what you mean?
searchPerson.CommandText = "SELECT * FROM Contacts WHERE Name LIKE '"+person+"%'";
searchPerson.CommandText =
"SELECT * FROM Contacts WHERE Name like #person + '%'"
searchPerson.CommmandText = "SELECT * FROM Contacts WHERE Name like '" + #person + "%'";
select * from Contacts WHERE Name like '%' + '"+#person+"' + '%'
select * from Contacts WHERE Name like '%' + '"+#person+"'
select * from Contacts WHERE Name like '"+#person+"' + '%'
This should work
"Select * from customer where FirstName LIKE '"+TextBox1.Text + '%'+ "' ";
if Field type is Nvarchar use this code:
"select * from Contacts where name like N'%"+person+"%'"
Just for reference!
string strQuery = "select Ac_Key from AccountDetails where (Ac_Name like '%'+#Ac_Name+'%');
SqlCommand cmb1 = new SqlCommand(strQuery);
cmb1.Parameters.AddWithValue("#Ac_Name", AccountName);
"SELECT * FROM table_name like concat(#persons,'%')"
I used it.
i have this sql query
"select * from table where name like ?"
but I want it to work as
"select * from table where name like ?* "
what is the query please
I am using access with c#
Add * to your parameter. I.e., instead of
myCommand.Parameters.AddWithValue("#search", searchValue);
use
myCommand.Parameters.AddWithValue("#search", searchValue + "*");
Keep your SQL as it is.
If you want to do a wildcard search (instead of a "literal *"), note that ADO.NET uses %, not *:
myCommand.Parameters.AddWithValue("#search", searchValue + "%");