I have to use "messageId" and "parrentId" c# variables in sql query, but when I use error raise: "Incorrect syntax near '.2'.".
How can I use "messageId" and "parrentId" in below query?
internal DataTable getAllMessages(string messageId, string parrentId)
{
Query = "SELECT DISTINCT T1.* FROM mail_Reply T2 JOIN mail_Messages T1 ON (T2."
+ messageId + "=T1." + messageId + " OR T2." + parrentId + "=T1."
+ messageId + ")";
return ExecuteDataTable();
}
Thanks in advance.
Don't try and build a query string like that - it opens you up to a vulnerablity known as SQL Injection - and that is something you need to go away and read about right now...
Once you're done with that, read about Command objects - SqlCommand and friends...
Alternatively, consider embracing Entity Framework...
if you column names are like integer values 1,2,3, then try this,
Query = "SELECT DISTINCT T1.* FROM mail_Reply T2 JOIN mail_Messages T1 ON (T2.["
+ messageId + "]=T1.[" + messageId + "] OR T2.[" + parrentId + "]=T1.["
+ messageId + "])";
return ExecuteDataTable();
use string.format or build the query seperatly in a string variable and assign it to Query
Related
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting
Here is the query
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
Exception image
here the image for exception i am getting after run this query
On your ...'"+x+"... you forgot to close the single quotes. You open them but you never close them after you add the X variable to your query. All SQL is seeing is "'0," which is invalid syntax.
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
I don't know why you need that on select columns. and you provided insufficient information and code on your question.
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)";
When i use this string as a sql command-string compiler gives me no error:
string sql = "SELECT * FROM Students WHERE StudentNo='" + T_No.Text + "'";
But, if i use this string (includes '%' character) it says "Error converting data type varchar to bigint":
string sql = "SELECT * FROM Students WHERE StudentNo='%" + T_No.Text + "%'";
What should i change in order to use '%' in my statement?
string sql = "SELECT * FROM Students WHERE convert(nvarchar,StudentNo) LIKE '%" + T_No.Text + "%'";
Note, however, that this is inefficient.
Take a look at the following page.
http://web.archive.org/web/20150519072547/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-search-for-special-characters-e-g-in-sql-server.html
The % sign has a special meaning in SQL.
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.
Ok, I have a list that consists of a bunch of values from a sql query, that part works fine. What I want to do is use the items in that list to tell another query what to look for. So, what it is saying is that, it should return all columns from CMMReports where PartNumber is like %listItem1..2...3%, Any advice?
List<string> ImportedParts = GetImportedPartNumbers();
string query = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND PartNumber LIKE %" + ImportedParts + "% ORDER BY CreatedOn DESC;";
Not that I condone this as you should be using parameterized queries. However, this should work:
StringBuilder partNumbers = new StringBuilder();
foreach (string queryValue in ImportedParts)
{
string q = "PartNumber LIKE '%" + queryValue + "%'";
if (string.IsNullOrEmpty(partNumbers.ToString())
{
partNumbers.Append(q);
}
else
{
partNumbers.Append(" OR " + q);
}
}
string query = string.Format("SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') " +
"AND (FilePath NOT LIKE '%js91162%') AND ({0}) " +
"ORDER BY CreatedOn DESC;", partNumbers.ToString());
You might look up the IN clouse for SQL that way you get the answer for the parts that SQL Server can find in the database. Using WHERE x = y for all the items means that if one item can't be found the whole query returns nothing.
I would consider doing this in a stored procedure and passing in your list as an Xml parameter.
See the following article for more info on using Xml parameters in a stored proc:
Passing lists to SQL Server 2005 with XML Parameters - By Jon Galloway
Form there you can easily use your list data inside your stored proc using the Xml syntax and treat it almost as another table of data.
Untested, but you should get the idea:
List<string> ImportedParts = GetImportedPartNumbers();
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND (";
int i = 0;
foreach (string part in ImportedParts) {
cmd.AddParameterWithValue("#param" + i.ToString(), "%" + part + "%");
if (i != 0) cmd.CommandText += " OR"
cmd.CommandText += " PartNumber LIKE #param" + i.ToString();
i++;
}
cmd.CommandText += ") ORDER BY CreatedOn DESC;";
This solution uses a parameterized query instead of just appending strings in the SQL, which is considered a potential security risk.