简体   繁体   English

MySql更新将无法正常工作

[英]MySql Update won't work

Good day! 美好的一天! I need help please.. This is my code on c# whenever I execute it nothing happens no error or hint 我需要帮助。.这是我在C#上的代码,每执行一次它就不会发生任何错误或提示

string myConnection = " datasource=localhost;port=3306;username=root;password=wolf";
        string Query = " UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate='" + txtToBeReturned.Text + "' WHERE bikeID='" + txtBikeIdRent.Text + "'"; 
        MySqlConnection myConn = new MySqlConnection(myConnection);
        MySqlCommand SelectCommand = new MySqlCommand(Query, myConn);
        myConn.Open();
        MessageBox.Show("Data Saved");
        myConn.Close();

I am not sure why the Upate won't work but when I execute this code on MySql 我不确定为什么Upate无法使用,但是当我在MySql上执行此代码时

UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';

It works just fine can someone help me? 效果很好,有人可以帮助我吗?

A command should be executed to do anything. 应该执行命令以执行任何操作。 Your code misses the call to SelectCommand.ExecuteNonQuery() line after the open connection. 您的代码在打开连接后会错过对SelectCommand.ExecuteNonQuery()行的调用。 However after fixing this trivial error you could encounter other problems with the values concatenated to form your command text. 但是,在修复了这个小错误之后,将值组合起来形成命令文本可能会遇到其他问题。 What if the user types an invalid date? 如果用户输入无效日期该怎么办? Have you ever heard of Sql Injection hacks ? 您是否听说过Sql Injection黑客

This is how your code should be written after adding validation to your inputs and parameters to send values to your database 这是在将验证添加到输入和参数以将值发送到数据库后应该编写代码的方式

int bikeID = 0;
if(!Int32.TryParse(txtBikeIdRent.Text, out bikeID)
{
     MessageBox.Show("Invalid number");
     return;
}
DateTime returnDate;
if(!DateTime.TryParse(txtToBeReturned.Text , out returnDate)
{
     MessageBox.Show("Invalid date");
     return;
}
string myConnection = ".....";
string Query = @"UPDATE bikerentaldb.tblbikes 
    SET status='Rented', renteddate=NOW(),
        assignedreturndate=@date
        WHERE bikeID=@id"; 
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand cmd = new MySqlCommand(Query, myConn))
{
     myConn.Open();
     cmd.Parameters.Add("@date", MySqlDbType.Date).Value = returnDate;
     cmd.Parameters.Add("@id", MySqlDbType.Int32).Value = bikeID;
     int rowUpdated = cmd.ExecuteNonQuery();
     if(rowUpdated > 0)
         MessageBox.Show("Record updated");
     else
         MessageBox.Show("No record match");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM