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 + "'%'";
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 have following query that works.
string sqlCommandText = "SELECT * FROM Admin_T where AdminID =
'" + textBox.Text + "'";
It is a fix command and I cannot use it with user given Table names and Column names at run time.
What I am actually trying to make is command like
string sqlCommandText = "SELECT * FROM Admin_T where
'" + UserGivenColumnName + "' = '" + conditionTB.Text + "'";
"UserGivenColumnName" can be any column that is part of that specific table.
Trying to create flexibility so that same command can be used under different circumstances.
SqlCommand and none of related classes used by ADO.NET does not support such a functionality as far as I know.
Of course your should never build your sql queries with string concatenation. You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
But prepared statements only for values, not column names or table names. If you really wanna put your input string to your column name, create a whitelist and use it as a validation before you put it in your query.
http://codeblog.jonskeet.uk/2014/08/08/the-bobbytables-culture/
I think an Object-Relational Mapper (ORM) is perhaps the droid you are looking for. Entity Framework might be a good place to start.
Please also do take the time to understand what SQL injection is, as the other users have also prompted you to.
It is not returning anything as it is just comparing two strings
With the 'UserGivenColumnName' it is a string comparison
And those two strings are not equal
You can do it (column) by just not including the '
But it is still a bad idea
SQLinjection is a very real and very bad thing
string sqlCommandText =
"SELECT * FROM Admin_T where " + UserGivenColumnName + " = '" + conditionTB.Text + "'";
or
string sqlCommandText =
"SELECT * FROM Admin_T where [" + UserGivenColumnName + "] = '" + conditionTB.Text + "'";
I'm having troubles trying to execute a SQL query with repeated parameters using entity framework.
The query is a keyword search, that looks in different tables, therefore using the same parameter many times. I'm using LIKE statements (yes, I know I should be using FULLTEXTSEARCH, but I don't have time for that right now).
I've tried all the syntax explained here: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5 and none of them make the query work (I get zero returned rows).
I even tried building a string array in runtime, with length equal to the number of times the parameter repeats in the query, and then populating all the elements of the array with the keyword search term. Then I passed that as the object[] parameters. Didn't work either.
The only thing that works is to make a search&replace that is obviously a bad idea because the parameter comes from a text input, and I'll be vulnerable to SQL injection attacks.
The working code (vulnerable to SQL injection attacks, but the query returns rows):
//not the real query, but just for you to have an idea
string query =
"SELECT Field1, " +
" Field2 " +
"FROM Table1 " +
"WHERE UPPER(Field1) LIKE '%{0}%' " +
"OR UPPER(Field2) LIKE '%{0}%'";
//keywordSearchTerms is NOT sanitized
query = query.Replace("{0}", keywordSearchTerms.ToUpper());
List<ProjectViewModel> list = null;
using (var context = new MyContext())
{
list = context.Database.SqlQuery<ProjectViewModel>(query, new object[] { }).ToList();
}
return list;
I'm using ASP.NET MVC 4, .NET 4.5, SQL Server 2008 and Entity Framework 5.
Any thoughts on how to make the SQLQuery<> method populate all the occurrences of the parameter in the query string? Thank you very much for your time.
Try this:
string query =
#"SELECT Field1,
Field2
FROM Table1
WHERE UPPER(Field1) LIKE '%' + #searchTerm + '%'
OR UPPER(Field2) LIKE '%' + #searchTerm + '%'";
context.SqlQuery<ProjectViewModel>(query, new SqlParameter("#searchTerm", searchTerm)).ToList();
You can use parameters in your query. Something like this
string query =
"SELECT Field1, " +
" Field2 " +
"FROM Table1 " +
"WHERE UPPER(Field1) LIKE #searchTerm" +
"OR UPPER(Field2) LIKE #searchTerm";
string search= string.Format("%{0}%", keywordSearchTerms);
context.SqlQuery<ProjectViewModel>(query, new SqlParameter("#searchTerm", search)).ToList();
how about try this
string query =
string.Format("SELECT Field1, Field2 FROM Table1 WHERE UPPER(Field1) LIKE '%{0}%'
OR UPPER(Field2) LIKE '%{0}%'",keywordSearchTerms.ToUpper());
context. Database.SqlQuery< ProjectViewModel >(query)
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 + "%");
I've got a error which I can't understand. When I'm debugging and trying to run a insert statement, its throwing the following exception:
"There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement."
I have looked all over my code, and I can't find the mistake I've made.
This is the query and the surrounding code:
SqlConnection myCon = DBcon.getInstance().conn();
int id = gm.GetID("SELECT ListID from Indkøbsliste");
id++;
Console.WriteLine("LNr: " + listnr);
string streg = GetStregkode(navne);
Console.WriteLine("stregk :" + strege);
string navn = GetVareNavn(strege);
Console.WriteLine("navn :" + navne);
myCon.Open();
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(" + id + "," + listnr + ", '" + strege + "','" + navn + "'," + il.Antal + ", "+il.Pris+")";
Console.WriteLine(il.Antal+" Antal");
Console.WriteLine(il.Pris+" Pris");
Console.WriteLine(id + " ID");
SqlCommand com = new SqlCommand(query, myCon);
com.ExecuteNonQuery();
com.Dispose();
myCon.Close();
First of all check the connection string and confirm the database location and number of columns a table has.
Suggestion : Do not use hardcoded SQL string. Use parameterized sql statements or stored-proc.
Try parameterized way,
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris)
Values (#ListID, #ListeNr, #Stregkode, #Navn, #Antal, #Pris)"
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.Add("#ListID",System.Data.SqlDbType.Int).Value=id;
com.Parameters.Add("#ListeNr",System.Data.SqlDbType.Int).Value=listnr;
com.Parameters.Add("#Stregkode",System.Data.SqlDbType.VarChar).Value=strege ;
com.Parameters.Add("#Navn",System.Data.SqlDbType.VarChar).Value=navn ;
com.Parameters.Add("#Antal",System.Data.SqlDbType.Int).Value=il.Antal;
com.Parameters.Add("#Pris",System.Data.SqlDbType.Int).Value=il.Pris;
com.ExecuteNonQuery();
Please always use parametrized queries. This helps with errors like the one you have, and far more important protects against SQL injection (google the term, or check this blog entry - as an example).
For example, what are the actual values of strege and/or navn. Depending on that it may render your SQL statement syntactically invalid or do something worse.
It (looks like) a little more work in the beginning, but will pay off big time in the end.
Are you using danish culture settings?
In that case if il.Pris is a double or decimal it will be printed using comma, which means that your sql will have an extra comma.
Ie:
INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(33,5566, 'stegkode','somename',4, 99,44)
where 99,44 is the price.
The solution is to use parameters instead of using the values directly in you sql. See some of the other answers already explaining this.