So I have the following code :
public static void WriteToDatabase(string sql,string value,int Amount, string URL)
{
int times = int.Parse(((dr)[dt.Columns[1]]).ToString()) + Amount;
sql = "UPDATE Words "+
" SET Amount = " + times +
" WHERE Word = " + value +
" AND Website = " + URL + ";";
myAdp = new OleDbDataAdapter();
myAdp.InsertCommand = new OleDbCommand(sql, myConn);
myAdp.InsertCommand.ExecuteNonQuery();
}
Which supposed to update a value in a pre-made Microsoft Access 2007 file,
and whenever I run the code they following OleDb exception occurs :
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll ,
Syntax error missing operator in query expression : 'Word = meta AND Website = http://www.twitch.tv/directory'."
"
So I've searched the web for common errors that could happen, and I couldn't find any,
I'll be glad if someone can find the mistake in the sql.
Thanks.
You absolutely should be using parameterized queries for this. That is the right way to pass values in.
Your problem is that your query is missing single quotes:
"UPDATE Words "+
" SET Amount = " + times +
" WHERE Word = '" + value + "'" +
" AND Website = '" + URL + "'"
But let me re-emphasize that although this should work, you should fix the code so it uses parameters
Assuming the Word field is a varchar, you have forgotten the necessary single quotes around the variable. " WHERE Word = '" + value + "'"
Related
I am doing a project with C# and I have this error:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near ' last_name= , email=
, phone= , address= WHERE id= 6' at line 1
I know this is a query error, but I tried many things and I don't see the issue.
My query is this:
cm = new MySqlCommand("UPDATE customers SET first_name= " + txtNombre.Text + "," + " last_name= " + txtApellidos.Text + "," + " email= " + txtEmail.Text + "," + " phone= " + txtTelefono.Text + "," + " address= " + txtDireccion.Text + " WHERE id= " + dgvClient.SelectedRows[0].Cells[0].Value.ToString() , con);
There should be single quotes around the text that you want to inject into the query, so it will look like this:
var query = "UPDATE customers SET first_name= '" + txtNombre.Text + "'";
This is the easiest solution but is advised against, mostly because of a possiblity for 'sql injection'. The easiest way to show this is by using the name O'Brian, because of the quote the database will think that the name is only O and then see it followed by Brian that it doesn't know what to do with and gives an error. Some people can use this to add other things to your query to cause harm to your database (like dropping tables or the whole database)
It is advised to use parameters, this solves this whole sql injection issue. Your code will look as follows:
cm = new MySqlCommand("UPDATE customers SET first_name=#first_name, last_name=#apellidos WHERE id=#id", con) ;
cm.Parameters.AddWithValue("#first_name", txtNombre.Text);
cm.Parameters.AddWithValue("#apellidos", txtApellidos.Text);
cm.Parameters.AddWithValue("#id", dgvClient.SelectedRows[0].Cells[0].Value.ToString());
It is best to always use parameters for your query, you can also look into using a framework like Entity Framework that does this automatically for you.
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.
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "=": syntax error (code 1): , while compiling: DELETE FROM notesWHEREid='1')
This is the error i am getting:
This is the part of my database handler that is the source of this error:
public void deleteNote(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
db.execSQL(deleteQuery);
db.close();
}
If you are using C# 6.0, using interpolated strings makes life much easier for strings concatenation, avoiding such silly errors:
String deleteQuery= $"DELETE FROM {DatabaseValues.TABLE_NOTES} WHERE {DatabaseValues.NOTES_ID} = id";
Note: $ operator is available in C# 6.0. Also you should take a look into how to build parameterized queries because passing parameters like this can expose you to SQL injection.
Change your following statement:
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
to
String deleteQuery= "DELETE FROM " + DatabaseValues.TABLE_NOTES + " WHERE " + DatabaseValues.NOTES_ID + " = '" + id + "'";
Actually you are combining the table name with where clause. You need to add a space before and after WHERE Clause like " Where "
Hope it helps.
I have created a program that monitors the progress of projects for my company but as i am testing i am encountering a very bizzare problem. When i test it under windows 10 in the pc it was created everything runs as expected. However when i test it in the computers of my co-workers that run windows 7 and 8 i get the following error in the sql query code "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'01 where teammember.Name="SomeName" and projects="SomeProject"' at line 1" . The code that results to the error is below.
public void UpdateHoursWorked(string teamMember, string projectName, float hoursWorked)
{
SetSafeUpdates(false);
// Error HERE
using (MySqlCommand cmd = new MySqlCommand("update memberprojects " +
"join teammembers on Member = teammembers.TeamMembersID " +
"join projects on Project = projects.ProjectsID " +
"set HoursWorkedOnProject = HoursWorkedOnProject + " + hoursWorked + " " +
"where teammembers.Name = \"" + teamMember + "\" and projects.ProjectName = \"" + projectName + "\"", conn))
cmd.ExecuteNonQuery();
// Update the total hours worked in the projects table, and re-read the projects
UpdateTotalHoursWorked(projectName, hoursWorked);
OnUpdate(EventArgs.Empty);
}
I can't seem to pin point the problem as under windows 10 the program works perfectly and the syntax looks correct to me. Any idea about what might cause the problem?
Write your query using Command.Parameters. Also use # to concatenate strings on multiple lines. Format your query !
Benefits:
1) Problems like this will not occur
2) You are protected from sql injection
3) The code is read/written easier
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = #"
UPDATE
MemberProjects
JOIN
TeamMembers ON Member = TeamMembers.TeamMembersID
JOIN
Projects ON Project = Projects.ProjectsID
SET
HoursWorkedOnProject = HoursWorkedOnProject + #HoursWorked
WHERE
TeamMembers.Name = #Name AND
Projects.ProjectName = #ProjectName";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#HoursWorked", hoursWorked);
cmd.Parameters.AddWithValue("#Name", teamMember);
cmd.Parameters.AddWithValue("#ProjectName", projectName);
cmd.ExecuteNonQuery();
}
I think you can see easily the difference between good formatting and using parameters. I advise you to write the Table names infront of Member, Project it will be easier to understand the location of this fields.
Try avoid double quotes sequence (and escape) using a proper alternance with single quotes
"update memberprojects " +
"join teammembers on Member = teammembers.TeamMembersID " +
"join projects on Project = projects.ProjectsID " +
"set HoursWorkedOnProject = HoursWorkedOnProject + " + hoursWorked + " " +
"where teammembers.Name = '" + teamMember + "' and projects.ProjectName = '" + projectName + "'", conn))
cmd.ExecuteNonQuery();
I managed to solve the final issue. My computer was using English Windows but my co-workers all use Widndows in our native language. In my country decimal numbers are written using a comma (example 0,0) but in the us decimal numbers are written with a dot (example 0.0) so when other pcs sent data to the database it was wrong. To fix the issue i changed the Thread.CurrentThread.CurrentCulture to new CultureInfo("en-us")
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.