I'm trying to perform a simple query on my MS Access DB from a Console Application through prepared statements.
The query tries to look for the desired value either in the "targa" field or in the "auto" field, to simplify the user interface with only one research label.
//grab field from GUI
string ricerca = Ricerca.Text;
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%?%'";
command = new OleDbCommand(queryTarga, con);
command.Parameters.Add("#p1", OleDbType.VarChar,ricerca.Length,"targa").Value = ricerca;
command.Parameters.Add("#p2", OleDbType.VarChar, ricerca.Length,"auto").Value = ricerca;
If I insert a known value for the first field "targa", the lookup works out with no issues.
If I insert anything for "auto", the lookup never returns any value!
The problem is that '%?%' gets interpreted in a weird way due to the single quotes and it's not recognising and setting the parameter correctly. By hardcoding the "ricerca" variable in the query string (without using '?') it works just fine:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%" + ricerca + "%'";
Does anyone have a clue of how to set the parameter?
try this:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE #p1";
command = new OleDbCommand(queryTarga, con);
command.Parameters.AddWithValue("#p1", "%" + Ricerca.Text + "%");
Related
I was wondering why this SQL Query doesn't return anything:
mySqlCommand.CommandText = "SELECT * FROM `users` WHERE Username LIKE %#Username% ORDER BY Id DESC";
mySqlCommand.Parameters.AddWithValue("#Username", this.search.Text);
IT's not a reader problem or anything like this, if i remove "WHERE Username LIKE %#Username% ", it works fine.
I call this whole MySQL-Query in a KeyPress-Event of a Textbox.
this.search is the Textbox. I want to search for rows where the Username Column contains the Characters i entered in the Textbox.
Try to use
//For LIKE query
SqlParameter parameter = new SqlParameter("#query", SqlDbType.NVarChar);
parameter.Value = string.Format("%{0}%", this.search.Text);
IList<Users> results = ctx.Database.SqlQuery<Users>("SELECT * FROM Users WHERE Username LIKE #query", parameter).ToList();
I solved it using this:
mySqlCommand.CommandText = "SELECT * FROM `users` WHERE Username LIKE #Username ORDER BY Id DESC";
mySqlCommand.Parameters.AddWithValue("#Username", "%" + this.search.Text + "%");
I would strongly recommend using a stored procedure, will help against SQL Injection attacks, and you want to disallow your app to use insert, update and delete scripts and only allow it to use execute statements for stored procedures.
But you want to change this line from
mySqlCommand.CommandText = "SELECT * FROMusersWHERE Username LIKE %#Username% ORDER BY Id DESC";
to
mySqlCommand.CommandText = "SELECT * FROMusersWHERE Username LIKE '%#Username%' ORDER BY Id DESC";
I am trying to pull data from my table based on the button a user clicks, so if they click the 1940's button it will pull all products from that decade but I cant get the query to work. It has to do with the #decade parameter because that is where I am getting the user input from but it doesnt like it when I am trying to choose a column using that parameter
ImageButton decadeBtn = (ImageButton)sender;
var decade = decadeBtn.CommandArgument;
yearHead.InnerText = decade.ToString();
string cmd="";
DataSet ds;
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is null";
}
using (OleDbConnection dbConn = new OleDbConnection(connectionString))
using (OleDbDataAdapter dbCmdDecade = new OleDbDataAdapter(cmd, dbConn))
{
dbConn.Open();
dbCmdDecade.SelectCommand.Parameters.Add("#decade", OleDbType.Integer).Value = decade;
dbCmdDecade.SelectCommand.Parameters.Add("#line", OleDbType.VarChar).Value = productLine;
ds = new DataSet();
dbCmdDecade.Fill(ds, "products");
}
No you can't use a parameter in that way. As a rule, you cannot use a parameter to define a column name or a table name (or concatenating it to form a column name). A parameter could only be used to define a value used in the query. (or with a stored procedure to create an SQL Text inside the sp to be executed but that is another more complex story),
However, assuming that you are not allowing your users to type directly the decade value (Sql Injection vulnerability), then it is pretty simple to create a string with the column name desidered and use it in your query.
Add a method that just concatenate together you decade string with your prefix for the DECADE column
private string GetDecadeColumn(string decade)
{
return "DECADE_" + decade;
}
and in you query
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is null";
}
So ARCHIVE_DECADE_TBL has columns that are named something like DECADE_1990 with a value of 1990, DECADE_2000 with a value of 2000, etc?
It really should be designed to just be called "DECADE" with the value being 1990/2000/etc, but if that's not possible, you'll have to build your query dynamically. I don't believe those parameters will work to set the column name. They can set a value to check for, but not the column names.
You'll have to build the query out manually in c#, so something like:
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_" + decade + #" = #decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
Now, if I misunderstood and your column is actually named DECADE_#decade, then I think you'll just need to change your variable so it's not #decade, so something like #mydecade. The conflict there will confuse it.
Sooooo like...
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#mydecade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
And then down below:
dbCmdDecade.SelectCommand.Parameters.Add("#mydecade", OleDbType.Integer).Value = decade;
That probably shouldn't have an # in the column name though. :)
I have problem with types mismatch - I think. I have application which connects with database and sends query. That is how it works:
string wartosc1 = "'letters'";
NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = "+wartosc1, conn);
but when I try to execute it, there is answer:
System.FormatException: Input string was not in correct format.
I suppose that there is problem with type of variable because when I just input:
SELECT * FROM RESOURCES WHERE TYPE ='letters'
Everything is ok.
Any ideas?
You need to use parameters to pass in the value to the query.
Read http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx on how to do that.
var wartosc1 = "letters";
var command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = #type", conn);
command9.Parameters.Add("#type", wartosc1);
Because when you write;
"SELECT * FROM RESOURCES WHERE TYPE = " + wartosc1
Your command will be like;
SELECT * FROM RESOURCES WHERE TYPE = letters
which is wrong because I suppose your TYPE column is some text type. If you solve this an easy way, you can add your wartosc1 variable inside single quotes like;
"SELECT * FROM RESOURCES WHERE TYPE = '" + wartosc1 + "'"
But please don't use this way.
You should always use parameterized queries in your commands. It prevents, forget to use some quotes, commas etc.. But more important this kind of string concatenations are open for SQL Injection attacks.
string wartosc1 = "letters";
NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = #type", conn);
command9.Parameters.AddWithValue("#type", wartosc1);
Here is an example of string Interpolation using several variables and a date:
var dt = DateTime.Now.AddDays(-30);
string wartosc1 = "letters";
string myStatement = $#"
SELECT *
FROM RESOURCES res
WHERE res.DATE_EXAMPLE >= '{dt}'
AND res.TYPE = '{wartosc1}'
"
BEWARE This sql string IS open to sql injection, simply by setting
wartosc1 = "somevalue' AND someOtherStatement 'thenDoSomethingBeforeApostrophe";
However, it may be that your environment doesn't need to worry about that... the apostrophes aren't necessary around an int, but forget it around a datetime, and you'll throw errors.
I'm making a simple asp.net/c# application and everything with the Oledb worked just fine until now.
The like statement is just not working through c#, it worked as a SQL Query in Access. I also tried just using '*a*' instead of '*#uname*' but it still didn't return anything.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(
"SELECT accounts.ID, uname, firstname, lastname, description FROM accounts, profiles " +
"WHERE accounts.ID = profiles.ID AND uname like '*#uname*'", connection);
dataAdapter.SelectCommand.Parameters.Add("#uname", OleDbType.VarChar).Value = tbxFilter.Text;
Well, from here I can see a fast way to fix it:
WHERE accounts.ID = profiles.ID AND uname like #uname
and then your parameter should be defined like this:
dataAdapter.SelectCommand.Parameters.Add("#uname", OleDbType.VarChar).Value = "%" + tbxFilter.Text + "%"
or
dataAdapter.SelectCommand.Parameters.Add("#uname", OleDbType.VarChar).Value = "*" + tbxFilter.Text + "*".
A side note: if I were you, I would not include the tbxFilter.Text directly. Instead, you should use this:
tbxFilter.Text.Replace("'", "''")
since a ' sign in your parameter will hurt your SQL query if not doubled. Either that or you perform this safety check on your text control's handlers.
The problem is that you're not using the correct wildcard character. Access can use either * or %, but most other use only %
Something like this works for me in my DB.
dataAdapter
.SelectCommand
.Parameters
.Add(new OleDbParameter("uname", "?" + tbxFilter.Text + "?"));
i`m doing
string sql = "select * from publisher where title like "'"+tbproperty.text+";
but it`s not working!
regards..
Use SqlParameter:
SqlCommand cmd = new SqlCommand("select * from publisher where title like #title");
cmd.Parameters.AddWithValue("#title", tbProperty.Text);
If you need to add more to the parameter, then do the following (E.g.: output parameter):
SqlParameter param = new SqlParameter("#param ", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(param);
This means you don't need to build the string per se and stops SQL injection.
With LIKE, if you expect begin/ends matches you need some wildcards such as '%', and I'm assuming that the user isn't adding those; but - important: don't concatenate user input. Ever; you want something like:
sql = "select * from publisher where title like #arg";
With #arg defined as a parameter, with value something like:
cmd.Parameters.AddWithValue("#arg", "%" + tbproperty.text + "%");
Correction..
string sql = "select * from publisher where title like '" + tbproperty.text + "'";