Updating SQL database entries - c#

I'm currently attempting to introduce an update option for my form project. I can successfully save entries to the database, but I want to be able to update these entries if the user gets information in the future that needs to be updated within the database...
Currently my error is, "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'"lossID=8, 25 Oct, 00:00, 25 Oct, 23:59,","" at line 1.
I thought this would be from perhaps the set syntax but I get the same error if I remove it or change anything there. I'm not sure if its because I am using parameters for my insert function, and perhaps just missing something?
My code for this is,
if (start_time.Text == end_time.Text)
{
MessageBox.Show("Please input a different ending time for the loss event");
}
else
{
string constring = "datasource=localhost;port=3306;username=root;password=1234; ";
string query = "update lossdatabase.losstable set (lossID= '" + this.textBox1.Text + "', #Start, #Start_Time, #End, #End_Time, #Equipment, #Event, #Responsibility, #Cause, #Reason, Capacity_Loss='" + capacity + "', Planned= '" + Planned + "', Scheduled='" + Scheduled + "', Prepared='" + Prepared + "', #Primary_Rate, #Primary_Volume, #Primary_Percentage, #Secondary_Rate, #Secondary_Volume, #Secondary_Percentage, #Comment) where lossID= '" + this.textBox1.Text + "' ;";
//Defines the connection string to allow data to be deposited into the database, along with defining the variables and columns for the data to be added to
MySqlConnection conLossDB = new MySqlConnection(constring);
MySqlCommand cmdLossDB = new MySqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("#Start", start_date.Text);
cmdLossDB.Parameters.AddWithValue("#Start_Time", start_time.Text);
cmdLossDB.Parameters.AddWithValue("#End", end_date.Text);
cmdLossDB.Parameters.AddWithValue("#End_Time", end_time.Text);
cmdLossDB.Parameters.AddWithValue("#Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Event", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Responsibility", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("#Cause", richTextBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Reason", richTextBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Rate", Rate_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Volume", Volume_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Percentage", Percentage_box.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Rate", Rate_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Volume", Volume_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Percentage", Percentage_2.Text);
cmdLossDB.Parameters.AddWithValue("#Comment", richTextBox3.Text);
//Defines which boxes to read in order to input the text from the defined boxes into the corresponding columns
MySqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("The loss entry has successfully been updated");
//Opens the database and carries out the defined command outlined in the code above
this.Close();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

How to fix "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'"?

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.

Don't update MS Access database with id

I try to write a program for updating data with id. When I write number for id (for example id=7), the program is run and works correctly. But when I write label text and convert to number, the code doesn't update and throws an error.
Here is my code:
private void yadda_saxla_update_Click(object sender, EventArgs e)
{
connect.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
// when i write "id=7" or other number data is update,
// but i want update with label text ( Convert.ToInt32( id_label.Text) )
// and gives error
cmd.Connection = connect;
cmd.ExecuteNonQuery();
connect.Close();
disp_data();
}
And the error is the following:
What can I do? Thanks...
As Others pointed it out in the comments you should not concatenate user inputs because it gives an attacking vector for SQL Injection. (or at least check for harmful inputs)
Otherwise the solution, I think, is that you should remove the ' because at the moment the command currently parsed as a varchar.
This part where id='"+Convert.ToInt32( id_label.Text)+"'" becomes where id='7' instead of where id=7
So unless your ID is stored as a varchar, this line should be changed
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
to
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id="+Convert.ToInt32( id_label.Text);

C#: Using label I display the current date and time in the form, but I can't add this data to SQL Server

Using a 'label' I can display the date and time on the form, but I can't insert it into SQL Server. I don't know how to call it in the String InsertQuery= ?.
Here is the 'label' code which is displayed in the form:
label5.Text = DateTimeOffset.Now.DateTime.ToLongDateString(); // Date
label10.Text = DateTimeOffset.Now.DateTime.ToLongTimeString(); // Time
Here is the 'save' button code which is inside the save.
conn.Close();
conn.Open();
String InsertQuery = "INSERT INTO Stocks_Item VALUES('" + combo_main_type.Text + "','" + txt_stock_code.Text +"')";
SqlDataAdapter execute = new SqlDataAdapter(InsertQuery, conn);
execute.SelectCommand.ExecuteNonQuery();
MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
I also created two columns in a SQL Server table Stocks_Item:
Main_Item_Type | Stock_code| Date | Time
Don't concatenate together your SQL queries! This opens the door to SQL injection attacks.
Use parametrized queries instead!
Also: do not use names like Date or Time for your column names - those are reserved T-SQL keywords - try to use something more expressive, something that belongs to your problem domain - not just these overly generic column names.
Something like this:
string insertQuery = "INSERT INTO dbo.Stocks_Item (StockDate, StockTime) VALUES(#StockDate, #StockTime);";
SqlCommand cmdInsert = new SqlCommand(insertQuery, conn);
// define and set parameters
cmdInsert.Parameters.Add("#StockDate", SqlDbType.Date).Value = DateTime.Now;
cmdInsert.Parameters.Add("#StockTime", SqlDbType.Time).Value = DateTime.Now.TimeOfDay;
conn.Open();
cmdInsert.ExecuteNonQuery();
conn.Close();
MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Your Code Shows you are working with Web Forms,so alter your query like below and it will work.
String InsertQuery = "INSERT INTO Stocks_Item VALUES('" + combo_main_type.Text + "','" + txt_stock_code.Text +"','" + label5.Text.ToLongDateString() +"','" + label10.Text.ToLongTimeString() +"')";

SQL Error = -804 (C# with firebird database)

I am trying to input data from four text boxes into a Firebird database. Every time I click the button that executes the following code, I get an "SQL Error = -804 Count of read-write columns does not equal count of values."
I'm not sure what this error means. The code I have is:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "User ID=sysdba;Password=masterkey;" +
"Database=localhost:G:\\nael.FDB; " +
"DataSource=localhost;Charset=NONE;";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
FbTransaction addDetailsTransaction =
addDetailsConnection.BeginTransaction();
string SQLCommandText = " INSERT into Invoice_Name Values" +
"('" + textBox1.Text + "',' "
+ textBox2.Text + "',' "
+ int.Parse(textBox3.Text) + "',' "
+ textBox4.Text + "',' "
+ "')";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText,
addDetailsConnection, addDetailsTransaction);
addDetailsCommand.ExecuteNonQuery();
addDetailsTransaction.Commit();
MessageBox.Show(" Details Added");
}
I bet one of your TextBox.Text values has a comma in it... Otherwise: Did you check to see if you are specifying the right amount of columns?
Basically, the SQL engine is complaining that you gave it a list of parameters and it is trying to fill those into the table Invoice_Name, except, it has too many values for the count of columns in that table. Try printing SQLCommandText to the output window (Debug.WriteLine(SQLCommandText)) and see if that is what you expect it to be...
You should also not be doing it this way... check this post here: Inserting into DB with parameters safe from SQL injection?

Problems with submitting text to access database

I have been experiencing problems to add text from a text box into an access database. It is a long piece of text and when I keep it to 3 or 4 sentences it is inserted with no errors but as soon as it appears to be too long I get the following error...System.Data.OledbException syntax error (missing operator)in the query expression.
I have a method in the web service which adds the information and it is with the length of the one textbox insersiont(in this case a review to a book) that causes the error.
Another odd feature to the web page is that the submit button fires only upon the second click...there is a post back on the first click and then only on the second click does the information actually insert into the databse. I do not think however that this is the reason for the initial error of not being able to insert a paragraph into the access database(the field of which I have set to memo).
Any possibility to shed some light as to why the error is occuring.
here is my actuall web method.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
It is with review where I get the error, the field of which I set to memo(in the access database.
Perhaps the review you're inserting into the database has single quotes in it? I ask because I don't see that they're getting escaped (turned into two single-quotes) in the code building the query, i.e.:
cmd.CommandText = #"INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES('" + title.Replace("'", "''") + "', '" + rating.Replace("'", "''") + "','" + review.Replace("'", "''") + "','" + ISBN + "', '" + userName + "')";

Categories

Resources