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)";
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.
I have the following code:
USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "'");
When I run this, I get the following error:
{"Incorrect syntax near ', '.\r\nUnclosed quotation mark after the
character string ''."}
I can't see what I'm doing wrong.. Anyone?
Man....Where to start with this...
First off, you should be using stored procedures that accept parameters (variables from your application code). Second, you should have a dataaccess layer in your application separating database calls and your user interface. I can't possible stress enough how important this is and how bad your current approach is. You will forever be fighting problems like this until you correct it.
But to address the question as it was asked...Your error is because your query string is malformatted. Use the debugging tools to view the string before it is sent to the database and then you should be able to quickly determine what is wrong with it. To troubleshoot, you can always cut and paste that string into SSMS, refine it there, and then make the necessary changes to your c# code.
First of all look at the answer of Stan Shaw, next take a look at the comment of Jon Skeet!
The first thing to do is stop building SQL like that... right now. Use parameterized SQL and you may well find the problem just goes away... and you'll be preventing SQL Injection Attacks at the same time.
They sayed everything that's important and just for the sake of giving you a direct answer:
You have a status + "'"); at your code which needs to be changed to status + "')"; ...
...like this one:
string statement = "USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "')";
Instead of concatenating values into your query you should use a parameterized query or a stored procedure.
A rewrite of your code could be something like (depending on datatypes, etc):
string commandText = "INSERT INTO Extract2_EventLog (userId, startTime, endTime, elapsedTime, actionType, [status]) VALUES (#userId, #startTime, #endTime, #elapsedTime, #actionType, #status)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#userId", li.userId);
command.Parameters.AddWithValue("#startTime", li.startTime);
command.Parameters.AddWithValue("#endTime", li.endTime);
command.Parameters.AddWithValue("#elapsedTime", li.elapsedTime);
command.Parameters.AddWithValue("#actionType", li.actionType == ActionType.REPORT ? "report" : "extract");
command.Parameters.AddWithValue("#status", status);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
You've forgot the " at the beginning. So your code reverts sql with non sql.
AND your example seems to be incomplete.
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
string query = "update library_database.members set name='" + txtname.Text + "', Adresss='" + richtxtadress.Text + "',";
query = query + "Status='" + cmbstatus.SelectedText + "',Type='" + cmbtype.SelectedText + "',";
query = query + "Date_expiry='" + dateofexpiry.Value.ToString("yyyy-MM-dd") + "',#IMG";
query=query+"' where id='";
query = query + txtid.Text + "'";
cmd = new MySqlCommand(query, con);
cmd.Parameters.Add(new MySqlParameter("#IMG", imgbt));
The exception occur SQL Santax error at line 1 near #IMG. Please help how can I solve it?
Looks like you forget to column name when you update your #IMG value.
It should be something like;
query = ... "ColumnName = #IMG" + ...
But please
ALWAYS use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Next time, when you get this kind of sql syntax error, first thing you should try is to run your query in your database manager. Then you can easily see what is wrong with your query and how you can fix it.
I have problem inserting boolean value into database.
I have simple structure:
struct
{
string name;
bool isStudent;
}
and I want to insert it into data base like this:
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + people1.isStudent + ")";
dbCommand.ExecuteNonQuery();
but i throws exception:
SQLite error no such column: True
Try using:
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', '" + people1.isStudent + "')";
Note that 'true' or 'false' will be quoted this way.
Or:
int val = isStudent ? 1 : 0;
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + val + ")";
1 will be used for true values and 0 for false values.
Use parameters and you won't have to worry about quotes or format of the values (besides, it is a good practice to avoid SQL injection):
dbCommand.CommandText = "INSERT INTO People (name, isStudent)
VALUES (#name, #isStudent)";
dbCommand.Parameters.AddWithValue("#name", people1.name);
dbCommand.Parameters.AddWithValue("#isStudent", people1.isStudent);
dbCommand.ExecuteNonQuery();
SQLite doesn't have a bool column type and you're constructing the SQL statement yourself. If you want to do that, then convert 1 and 0 back and forth.
I would also think the .net wrapper would do that 4 u. But you would have to use SQL parameters and not build the string yourself to even give it a chance to do that.
Building parameterized queries (?) also let's SQL lite cache the compiled statements.