SQL and ASP.NET WHERE IN generates wrong - c#

I have this line of code:
sql += " AND lc.name IN ('" + String.Join(",", id.type.ToArray()) + "')";
There are two items in id.type and this code generates this:
AND lc.name IN ('towns back to back,towns 3 storey')
Which will not work because it should be like this:
AND lc.name IN ('towns back to back' , 'towns 3 storey')
How can I fix this?

This is not a desirable approach, because it's open to SQL injection. But there are a few things:
You have to accommodate for strings that contain single quotes.
It won't work if you just concatenate. You have to wrap EACH item in single quotes.
Try:
sql += " AND lc.name IN (" + String.Join(",", id.type.ToArray().Select(i=>String.Format(i.Replace("'","''"),"'{0}'")) + ")";

Use parameter to pass input string like
sql += " AND lc.name IN (#inputname)";
sqlcommand.parameters.AddWithValue("#inputname", String.Join("','", id.type.ToArray()))

Related

Using parameterized SQL LIKE Statements

I'm trying to parameterize my SQL Statements but I'm having some trouble with the LIKE statement. I tried different solutions but nothing works. My code:
sqlCmd = new SqlCommand("SELECT " + form1.cusId.Text + "," + form1.cusName.Text" FROM " + form1.getTable() + " WHERE " + form1.getCusId() + " LIKE #filterCustomers", connection);
sqlCmd.Parameters.AddWithValue("#filterCustomers", form1.filterCus().Trim() + "%");
I'm getting
"Must declare the scalar variable #filterCustomers".
Why ist that happening? Since this is th common solution...
What if you try
sqlCmd.Parameters.Add("#filterCustomers",SqlDbType.VarChar,8).Value = form1.filterCus().Trim() + "%";
Instead of:
sqlCmd.Parameters.AddWithValue("#filterCustomers", form1.filterCus().Trim() + "%");
You can change the.VarChar for what you data type is and the 8 for the required max field lenght, or remove the ,8 completely for no limit in the parameter lenght
you need to put your string inside single quotes ':
...+" LIKE '"+ form1.filterCus().Trim()+"%'", connection);
if you don't worry about SQL INJECTION
EDIT: you can also use dynamic sql:
sqlCmd = new SqlCommand("EXEC ('SELECT..... WHERE FIELD LIKE ''' + #filterCustomers + '%''')", connection);
sqlCmd.Parameters.AddWithValue("#filterCustomers", form1.filterCus().Trim() + "%");

Make a query dynamically depending on ComboBox choice

I am making a query involving 2 tables in C#. The query works fine when I input information into all the combo boxes. But when I try to make query with some empty combo boxes, it returns nothing.
I get that it is cos the string ends up having "" in the query which makes it invalid. Is there anyway I could restructure my query to make it possible to make queries with missing entries or even a missing secondary table? Thanks for advice.
The following works when I fill up all fields and make the query:
If I fill up only paritial fields as follows, it won't work:
My query String:
string query = #"SELECT Agents." + comboq1.Text + ", Agents." + comboq2.Text + ", Agents." + comboq3.Text + ", Agents." + comboq4.Text + ", "
+ secondaryTable.Text + "." + stCombo1.Text + ", " + secondaryTable.Text + "." + stCombo2.Text
+ " FROM Agents INNER JOIN " + secondaryTable.Text + " ON Agents.Dept_ID" + "="
+ secondaryTable.Text + ".Dept_ID";
string agentsValue = string.empty;
if (!comboq1.Text.equals(string.empty))
{ agentsValue = "Agents."+comboq1.text; }
if (!agentsValue.equals(string.empty))
{ agentsValue +=","; }
if (!comboq2.Text.equals(string.empty))
{
if (agentsValue.equals(string.empty))
{ agentsValue = "Agents."+comboq2.text; }
else
{ agentsValue += "Agents."+comboq2.text; }
}
please follow the above code for rest of the combo boxes and while adding the value of the second combo box add a comma in between the values. After building the string in this format you can then append it to your query and now when you execute the query you should not find any kind of errors.
Hope this helps
I would suggest that you use a separate string by checking that if any combo box does not provide any value then omit that combo box value from the string and then append the final string to you query which will not cause any problem.

SQL error in asp.net

if you please help me i am having a problem in sql code asp.net C#.
my error is:
System.Data.SqlClient.SqlException was unhandled by user code
Message=Incorrect syntax near ')'.
and my query code goes as follows:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + "," + null + ")";
You can't insert null like that way. Use parameterized query.
string query = "insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values (#overall_rating,#paper_id,#conference_role_id,#details)";
cmd=new SqlCommand(query,cn);
cmd.Parameters.AddWithValue("#overall_rating",0);
cmd.Parameters.AddWithVaule("#paper_id",ListBox2.SelectedValue);
cmd.Parameters.AddWithValue("#conference_role_id",Listbox1.SelectedValue);
cmd.Parameters.AddWithValue("#details",DBNull.Value);
Yes, as everybody else said already, you can't use null the way you are doing it but there are more serious issues than that:
Your sql statement is prone to SQL Injection attacks because you are not parametrizing your query
If you are not inserting a value into a column, simply don't list the column! This will work:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue +")";
I think the null is probably making things angry:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(0," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + ",null)";
You'll notice I made your 0 part of the string and made the null part of the string (instead of concatenating integer 0 and a NULL value with the string)
What you are doing with this example is you are creating a SQL string that you plan on sending to the Database that will be executed there. When you are making your string the result of the string is something like...
"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails) values(0, someValueFromListbox4,someOtherValueFromListbox1,)"
You will notice that the final parameter is missing. To fix this try this...
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + ",NULL)";
Here is another example using string.format which I would reccommend
string query = String.format("Insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails) Values(0,{0},{1},NULL)", ListBox4.SelectedValue, ListBox1.SelectedValue);
Try putting the null within the speech marks so the end looks like ",null)";

Building SQL "where in" statement from list of strings in one line?

I have a List(Of String) which corresponds to "types" on our database table.
We are using the DB2 ADO.NET provider and my final query needs to look something like this:
select * from table where type in (#type1, #type2, #type3, #type4)
In the past, I've built the list of query parameters / host variables using a ForEach loop, but I would really like to figure out a way to build them in one line. Of course, I can join all of the strings, but adding the "#" and the incrementing digit is giving me headaches.
Anyone have any ideas on how to do this?
Won't something like this work?
var inList = "(" + string.Join(", ", typeList.Select(t => "#" + t)) + ")";
Edit
Based on your comment, how about this?
var inList = "(" +
string.Join(", ", Enumerable.Range(1, argCount).Select(i +> "#type" + i)) +
")";
This is how I generally do this
string.Join(",", items.Select(i => $"'{i}'");
string dbCommand =
string.Format("select * from table where type in ({0})", string.Join(",", typeList.Select(p => "#" + p));
Split the list using as string.Join(",", listType.ToArray())
string types = string.Join(",", listType.ToArray());
Select * from table where type in (types)
A simple way could be to use :
"'" + string.Join("','", myListOfNames) + "'")
SQL/ADO.NET does not support arrays. So you really have to build the SQL by hand.
SQL 2008 does support a Table parameter, but it seems a lot of overhead. See http://www.sommarskog.se/arrays-in-sql-2008.html for more details.

DateTime.Now to mysql datetime

i got problem with a query, got something like this
command.CommandText = "SELECT " +
"COUNT(a.`id`) " +
"FROM " +
"`messageaccess` a " +
"WHERE " +
"a.`Users_LOGIN` = '" + Settings.UserLogin + "' " +
"AND a.`Status` = '" + Enums.MessageStatus.New + "' " +
"AND a.`FOLDER` = '" + Enums.MessageFolder.INBOX + "'" +
"AND a.`ShowAlert` = '" + Enums.YesNo.No + "'" +
"AND a.`Postponed` <= " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "";
but sql throws me exception
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:40:37' at line 1
tried diffrent combinantions but nothing works :(
The simple answer is not to embed values directly into the SQL to start with.
Use a parameterized SQL statement, specify the parameter value as DateTime.Now, and all will be well:
Your SQL will be easier to read (as it'll just be the code, not the data)
You won't need to worry about formatting of things like numbers and dates
You won't be vulnerable to SQL injection attacks
You forgot the quotation marks around the date/time thing.
try using this line instead:
"AND a.`Postponed` <= NOW()"
and it should work with the native MySql function for the current time.
Have a look at named parameterized queries. They take care of these formatting issues for you.
You shouldn't build your query appending strings. This is not very safe (sql injection) and you're not taking advantage of the ADO .NET capabilities to set the correct format according the parameter type.
You should use parametrized queries.

Categories

Resources