I am fairly new to C#, and i am trying to make a teacher management program.
This is the function that i am using to execute the query.
string commentString = "sC" + (y + 1) + "Y" + (i + 1) + "";
executeQuery("UPDATE student SET " +
commentString + " = '" + s.getStudentCourses(i,y,s)+
"' WHERE sNumber = '" + s.getStudNumber(s) + "'");
My Query String:
query "UPDATE student SET 'sComments1-1' = 'wa5235' WHERE sNumber = 68721919" string
The exception i get:
[MySql.Data.MySqlClient.MySqlException] {"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 ''sComments1-1' = 'wa5235' WHERE sNumber = 68721919' at line 1"} MySql.Data.MySqlClient.MySqlException
Here is the SQL data structure:
CREATE TABLE `NewTable` (
`sNumber` int(9) NOT NULL ,
`sFirstName` varchar(32) NOT NULL ,
`sLastName` varchar(32) NOT NULL ,
`sDOB` varchar(9) NOT NULL ,
`sGrade` int(1) NOT NULL ,
`sEmail` varchar(32) NULL ,
`sParentName` varchar(32) NOT NULL ,
`sParentPhone` varchar(11) NOT NULL ,
`sHomeAddress` varchar(32) NOT NULL ,
`sComments1-1` varchar(255) NOT NULL ,
Using MySQL 5.5
I do not know why, but this is giving me sql errors. Please help me, my assignment is due in 2 days and i really need this finished.
A duplicate of your problem (minus signs in column names) is asked and answered here:
MySQL INSERT - Do field names require backtick/accent delimination?
You need to use 'back-ticks' instead on single quotes when using the column name with a minus sign in your query. Like this:
UPDATE student SET `sComments1-1` = 'wa5235' WHERE sNumber = 68721919
There doesn't appear to be any way to get sComments1-1 from "sC" + (y + 1) + "Y" + (i + 1) + "" so I'm not sure why you think your query string is of the correct form.
In any case, your column names need to be surrounded by backticks rather than single quotes:
UPDATE student SET `sComments1-1` = ...
Assuming that sComments1-1 is a typo or earlier version, and should actually be one of multiple columns of the form sCaYb, where a and b are distinct integers, the code would look something like this:
// Get column name of form sC*Y* where *'s are distinct integers.
string commentColumn = "sC" + (y + 1) + "Y" + (i + 1);
// Execute query with correct quote types.
executeQuery("UPDATE student SET `" + commentColumn + "` = '" +
s.getStudentCourses(i,y,s) +
"' WHERE sNumber = " + s.getStudNumber(s));
I've added the backticks around the column name and removed them from the sNumber value (since it's an integer rather than a character column).
Have you tried removing the single quotes around your field names? unsure this will work but it's one thing i'd try.
if this doesn't help, let me know and i'll remove this answer
"UPDATE student SET 'sComments1-1' = 'wa5235' WHERE sN....
The Columnname 'sComments1-1' shouldnt be as a quoted string, just write the column name without the Quotes.
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 been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won't work.
My group has been looking at different solutions online but everything won't seem to work.
{
connection.Open();
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Updated Successfully!");
}
The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is "Microsoft Engine database" which does not save the changes.
The error says "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'" pointing to cmd.ExecuteNonQuery();
First, never use string concatenation to build a query. You're asking for a SQL Injection attack. The biggest thing I could see here is make sure that only columns that are string columns (varchar, char, text, etc..) have single-quoted values. Is cost a number? If so then it should be:
, cost=" + treatCost.Text + ",
If cost is a number, also make sure that there isn't a currency amount in the input field. If someone puts in 1,422.00 it's not a number and will fail since , is for decoration.
If someone puts in $1422.00 it's not a number as $ is for decoration.
Either of these would fail the query.
This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string. But much worse things can happen if the user knows a bit of sql and wants to cause trouble. For example, putting '-- in the remarks will result in
Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'
which will overwrite every row in the table, not only the one containing foobar.
Use query parameters so that user-provided values can't be interpreted as query keywords and structure.
Instead of remarks = '" + appRemarks.Text + "' you will have remarks = #Remarks as well as
cmd.Parameters.Add("#Remarks", SqlDbType.NText).Value = appRemarks.Text;
and all the other user inputs likewise.
I have an SQL request where I need to concatenate data into the request:
if (dataChoosen != "randomValue")
{
sCondition = " WHERE RandomField = '" + dataChoosen + "' ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
As I need to concatenate the condition, I don't think I can use a prepared request?
Also, I already tryparse the 'dataChoosed' value because it comes from a textbox and I need an integer. So is the the tryparse enough to prevent SQL injection?
I would just use parameters, there's no reason not to.
if (dataChoosed != "randomValue")
{
sCondition = " WHERE RandomField = #dataChoosed ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
cd.Parameters.Add("#dataChoosed", SqlDbType.VarChar).Value = dateChoosed;
No, you are not on the safe side. Even if dataChoosed is an innocent integer value, bad boys can hurt you with, say, negative value format:
// It's good old "-1", with a bit strange format
// (let use "delete from table commit;" as an injection)
string dataChoosed = "1'; delete from table commit; --1";
// A little hack: let "-" sign be...
CultureInfo hacked = new CultureInfo("en-US");
hacked.NumberFormat.NegativeSign = "1'; delete from table commit; --";
Thread.CurrentThread.CurrentCulture = hacked;
if (dataChoosed != "randomValue")
{
int v;
// since "1'; delete from table commit; --1" is of correct fotmat it will be parsed
if (int.TryParse(dataChoosed, out v))
sCondition = " WHERE RandomField = '" + dataChoosed + "' ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
And, woe! Where's my table? The command text will be
SELECT xData FROM table = '1'; delete from table commit; --1'GROUP BY xxx
which is efficently two queries:
SELECT xData FROM table = '1'; -- the innocent one
delete from table commit; -- an arbitrary query from the attacker
(I've removed commented out --1'GROUP BY xxx fragment)
Please, use parameters, do not tempt us. Please, notice, that you don't want to change code: all you have to do is to change the Regional Settings in your Windows.
Does [BLANK] protect against sql injection?
Unless [BLANK] is 'parameters' the answer is always no.
how to create table query in c# for mysql database..
MySqlConnection con = new MySqlConnection("Server=localhost;Database=demo_test;UID=root;Password= ");
MySqlCommand acmd = new MySqlCommand("CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment,'" + a.Columns[1].ToString() + "' varchar(100) NOT NULL default,PRIMARY KEY (" + a.Columns[0]+") 1", con);
con.Open();
acmd.ExecuteNonQuery();
it gives me an error
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 ''name' varchar(100) NOT NULL default,PRIMARY KEY (id) 1' at line
1
Instead of fighting with SQL directly, you could use Mig# like this:
var schema = new DbSchema(ConnectionString, DbPlatform.MySql5);
schema.Alter(db => db.CreateTable("first")
.WithPrimaryKeyColumn(a.Colunns[0], DbType.Int32).AsIdentity()
...);
It's because you are wrapping the column names with single quote which converts the value into string and not an identifier anymore. Remove the single quotes and it will work.
string query = #"CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment, "
+ a.Columns[1].ToString() + " varchar(100) NOT NULL default,
PRIMARY KEY (" + a.Columns[0]+")"
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)";