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())
{
...
}
}
Related
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.
I am looking to perform a greater than or less than search on multiple columns from an access database in C#.
So far I am trying to compare a chassis number value that is stored in a access database against a value in a textbox. If that value is greater than the textbox, this would then return the relevant data stored in the database to a gridview.
so far my code is:
var sql = "SELECT * FROM [database] WHERE (Manufacturer ='" + comboBox3.Text +
"' OR Manufacturer='*') AND (Model ='" + comboBox4.Text + "' OR Model='*') AND (Fuel ='" +
textBox9.Text + "' OR Fuel='*') AND (Chassisno='*' OR (Chassisno > '" + textBox2.Text + "'))";
The code above is finding results, but the 'greater than' operator is being ignored.
Does anybody have any ideas why this would be?
This portion:
Chassisno='*'
Causes the query to find anything. Please remove that part of the query if you are truly only interested in finding values that are greater than Chassisno.
you can't use * wild card with "=" , you should use "like" keyword :
.....OR Manufacturer like '*') AND (Model ='" + comboBox4.Text + "' OR Model like '*') AND (Fuel ='" +
textBox9.Text + "' OR Fuel like '*') AND (Chassisno like'*'....
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%"));
I am getting the following error
syntax not correct near item number
but I don't see anything wrong, the values being inserted are from a dataset containing field names in variables from another sql query that is being looped through and then inserted into another table like so....
string strOrderDetails =
"INSERT INTO Orders (Order Number, Item Number, Description, Price) " +
"VALUES ('" + strOrderNo.Replace("'", "''").ToString() + "', '"
+ intItemNo + "', '"
+ strDesc.Replace("'", "''").ToString() + "', '"
+ decPrice + "')";
On execution of the above is where the code falls over and states there's an error near the word item number?
Do I need to do something to the intItemNo as it's an integer?
When a column contains spaces you need to enclose it in square brackets or other delimiter for the choosen database
But said that, please do not use string concatenation to build sql commands, but always a parameterized query.
string strOrderDetails = "INSERT INTO Orders ([Order Number], [Item Number]," +
"Description, Price) VALUES (#ordNum, #temNo, #desc, #price";
using(SqlConnection cn = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand(strOrderDetails, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ordNum",strOrderNo);
cmd.Parameters.AddWithValue("#itemNo",intItemNo);
cmd.Parameters.AddWithValue("#desc",strDesc);
cmd.Parameters.AddWithValue("#price", decPrice);
cmd.ExecuteNonQuery();
}
As you could notice, using parameters remove the need to write code to handle quotes in the input values, but also remove the possibility of Sql Injection attacks
I have web search form, When i submit my search in the search box,
The result are returned but with contains % in the file name.
for example. the original file name is abc.jpeg, so the result returned will be a%bc.
or if a folder is found with, so its the same for the folder name.
if a folder name is jack, in the result it will be ja%ck.
I have the text box (as a search box, and i have set the value of the search text box as) <%search text%>
Thanks for the help and taking time to read it.
I am using Asp.net, C# and Access DB.
code :
iscBuilder.AddSelect("* ");
iscBuilder.AddFrom("[table1] ");
iscBuilder.AddWhereClause("( column_name like('%" + pQuery + "%') or column_name like('%" + pQuery + "%') or column_name like('" + pQuery + "%') or column_name like('" + pQuery + "%') )");
iscBuilder.AddWhereClause("(column_name like( '" + path + "') or column_name like( '" + path + "')) order by column_name");
OleDbConnection sqlconConnection = (OleDbConnection)DatabaseConnection.Instance.GetConnection();
OleDbCommand sqlcmdCommand1 = new OleDbCommand(iscBuilder.ToString(), sqlconConnection);
sqlcmdCommand1.CommandType = CommandType.Text;
This is how i call the function: public XmlDocument GetSearchResults(string pQuery, string path,int from , int to)
{
List <T> ts= T.GetF().Getresult(pQuery, path);
return createXMLThumnails(thmbNails,from , to);
}
Have nice day
Try using a parameterised query or stored procedure to get your data - all this joining strings to make SQL statements is very fiddly and problematic.
Have a look at using Parameterised Queries or Stored Procedures.