I am currently writing a Search function that bring down a value Name
Here is my query:
"SELECT Company.Name, Company.Reg FROM Company WHERE Name LIKE '%''" + Name + "''%'";
Here is the function:
public object CompanySearch(string Name)
{
using (PCE)
{
SqlConnection con = new SqlConnection(constr);
try
{
List<CompanySearch> cm = new List<CompanySearch>();
SqlCommand command = new SqlCommand();
command.Connection = con;
"SELECT Company.Name, Company.Reg FROM Company WHERE Name LIKE '%''" + Name + "''%'";
con.Open();
//process the sql execute etc
}
}
}
Is the way I reading Name correctly?
I tested without ' ' , however I get an exception message as follow:
"ExceptionMessage": "Incorrect syntax near 'Mysearch'.",
UPDATE
SELECT Company.Name, Company.Reg
FROM Company
WHERE CompanyName LIKE '%MySearch%';
This is the code that I execute in SSMS, and it went sucess. However it doesnt work on my C#
FROM, and you got too many single quotes.. And, perhaps most importantly, you should parameterize your query.MysearchwithMysearch' ; DROP TABLE Company; --(in the UI). By the way, you should back up your database before attempting this. Once you've realised the damage SQL injection can do, see HoneyBadger's suggestion of parameterising your query.MySearch' ; DROP TABLE Company; --then the final query will be:SELECT Company.Name, Company.Reg FROM Company WHERE CompanyName LIKE '%MySearch' ; DROP TABLE Company; -- %';: Two SQL commands (a select and a drop table) and then a comment. This is why you should use parameters instead.