mysql How to fix my update statement in C# API?

iezvtpos  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(79)

I wrote this below code and I am not able to update fields.
There is no error message, however my data is not getting updated.

public void UpdateTeacher(int id, [FromBody]Teacher TeacherInfo)
{
        MySqlConnection Conn = Teachers.AccessDatabase();

        //Open the connection between the web server and database.
        Conn.Open();

        //Establish a new command(query) for our database.
        MySqlCommand cmd = Conn.CreateCommand();

        cmd.CommandText = "update teachers set teacherfname=TeacherFname, teacherlname=TeacherLname, employeenumber=EmployeeNumber,salary=Salary where teacherid=TeacherId";
        cmd.Parameters.AddWithValue("@TeacherFname", TeacherInfo.TeacherFname);
        cmd.Parameters.AddWithValue("@TeacherLname", TeacherInfo.TeacherLname);
        cmd.Parameters.AddWithValue("@EmployeeNumber", TeacherInfo.EmployeeNumber);
        cmd.Parameters.AddWithValue("@Salary", TeacherInfo.Salary);
        cmd.Parameters.AddWithValue("@TeacherId", id);
        cmd.Prepare();

        cmd.ExecuteNonQuery();

        Conn.Close();
}

I tried insert and delete, they are working, however update query is not working.

vkc1a9a2

vkc1a9a21#

If you look at how you are adding your parameters, you stated that the parameter name starts with an '@' symbol.

cmd.Parameters.AddWithValue("@TeacherFname", TeacherInfo.TeacherFname);
...

But if you look at your SQL text, you have not used the '@' symbol, so you need to add this at the front of all your parameter names.

cmd.CommandText = "update teachers set teacherfname=@TeacherFname, teacherlname=@TeacherLname, employeenumber=@EmployeeNumber,salary=@Salary where teacherid=@TeacherId";

As also stated in the comments, using AddWithValue is generally considered bad. See this for more details: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

相关问题