美好的一天!我需要帮助... 这是我在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();
我不确定为什么Upate不起作用,但是当我在MySql上执行此代码时
UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';
有人可以帮助我吗?
答案 0 :(得分:2)
应执行命令以执行任何操作。您的代码在打开连接后错过了对SelectCommand.ExecuteNonQuery()行的调用。但是,在修复此琐碎错误之后,您可能会遇到其他问题,这些问题与连接的值形成命令文本有关。如果用户键入无效日期怎么办?你听说过Sql Injection hacks吗?
这是在为输入和参数添加验证后向您的数据库发送值
后编写代码的方式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");
}