-1

I am writing a student database program on C# using MySql. I want to update the information but it's always giving me that error. Here is the program I wrote.

private void Update_bttn_Click(object sender, EventArgs e)
{
    string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
    string Query = " Update studentdata.studentrecord set (CourseId = '" + this.crsId.Text + "', CourseName = '" + this.crsName.Text + "',Credits = '" + this.credits.Text + "', CourseStatement = '" + this.CrseStatment.Text + "',Grade = '" + this.Grades.Text + "' where CourseId = '" + this.crsId.Text+"' ; ";
    MySqlConnection ConDatabase = new MySqlConnection(ConString);
    MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
    MySqlDataReader myReader;

    try
    {
        ConDatabase.Open();
        myReader = cmdDataBase.ExecuteReader();
        MessageBox.Show("Information Updated");
        while ((myReader.Read())) { }
        ConDatabase.Close();
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
guetty
  • 13
  • 4
  • 2
    You are opening a bracket `(CourseId` but not closing it anywhere in your code. Do not concatenate queries, use Parameters. Your current code is prone to SQL Injection. – Habib Jun 11 '14 at 17:15
  • 1
    @Habib, that's an answer. – Rahul Jun 11 '14 at 17:16
  • i have put the )" but still the same output :s any other advice plz ? – guetty Jun 11 '14 at 18:02
  • Use the debugger to grab the actual value of `Querry` before you execute it. Grab the value of it and try to execute that command directly against your Database. That should give you a more detailed error at least – Jfabs Jun 12 '14 at 17:59

2 Answers2

0

For future reference, you can grab the value of query through debugging and attempt to run the actual query in SQL to get a more precise error. In this case however, it is because you have an open parentheses (CourseId... and no close ) later in the string.

Also, you may want to look into some documentation surrounding your use of the Sql classes in C#

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jfabs
  • 543
  • 4
  • 9
  • 23
0

Use parameterized query to avoid SQL injection

How does SQLParameter prevent SQL Injection?

you have ( near CourseId

string query = update studentdata.studentrecord set CourseId =@CourseId,CourseName=@CourseName,Credits =@Credits,CourseStatement=@CourseStatement,Grade =@Grade  where CourseId =@CourseId";

MySqlConnection ConDatabase = new MySqlConnection(ConString);

MySqlCommand cmdDataBase = new MySqlCommand(query, ConDatabase);

cmdDataBase.Parameters.AddWithValue("@CourseId",this.crsId.Text );
cmdDataBase.Parameters.AddWithValue("@CourseName", this.crsName.Text);

and so on

Community
  • 1
  • 1
Nagaraj S
  • 13,316
  • 6
  • 32
  • 53