当我点击按钮时,我正在尝试将时间更新到我的数据库中,但我在粗体部分出错:
(startTime = dr [0]。 ToString ();)
我该如何解决?
private void confirmbutton_Click(object sender, EventArgs e)
{
availabilitytabControl.SelectedTab = checkouttabPage;
startTime = Convert.ToDateTime(checkintimelabel.Text);
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = myAccessConnection();
OleDbCommand myAccessCommand = new OleDbCommand();
try
{
myAccessConn.Open();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myDataAdapter.Fill(myDataSet, "Time");
DataTableCollection dta = myDataSet.Tables;
DataColumnCollection drc = myDataSet.Tables["Time"].Columns;
DataRowCollection dra = myDataSet.Tables["Time"].Rows;
string startTime = null;
foreach (DataRow dr in dra)
{
*startTime = dr[0].**ToString**();*
}
string sqlStatement = "update Orders set Checkin_time=" +
startTime + " where OrderNo='" + receiptNo + "'";
myAccessCommand = new OleDbCommand(sqlStatement, myAccessConn);
myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myAccessCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(
"Error: Failed to retrieve the required data from the DataBase.\n{0}",
ex.Message);
return;
}
finally
{
myAccessConn.Close();
}
}
答案 0 :(得分:0)
startTime是DateTime类型,你试图为它分配一个字符串,为什么不这样做:
startTime = Convert.ToDateTime(dr[0].ToString());
答案 1 :(得分:0)
你永远不应该尝试将DateTime值作为字符串传递给数据库(除非你知道你在做什么 - 只应该使用ODBC Canonical格式)。
其次,正如@soner所说,代码中存在更严重的问题。您没有使用参数,因此对SQL注入攻击开放。
DateTime dt;
DateTime? startTime = ( DateTime.TryParse( checkintimelabel.Text,
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out dt )
? dt
: (DateTime?)null;
// ...
您的foreach循环没有任何意义,因此无需更正该部分但完全删除(数据适配器都没有用途)。
string sqlStatement = @"update Orders
set Checkin_time=@checkIn
where OrderNo=@orderNo";
var cmd = new OleDbCommand(sqlStatement, myAccessConn);
cmd.Parameters.AddWithValue("@checkIn", startTime);
cmd.Parameters.AddWithValue("@orderNo", receiptNo);
cmd.ExecuteNonQuery();