我正在从事小型项目并且是编码的新手,我希望该系统成为预订系统,只要在特定日期预订特定巴士,那么该巴士将特定于该日期。例如,Bus12被预订为在8月21日使用,则如果管理员错误地尝试预订同一辆公共汽车,则其他原因将基于检查日期和busno阻止该预订。我只是在使用Web表单,下面是我的数据库表,后面是代码。请帮我没有收到任何错误,刷新时我的数据库表中什么都不会存储。我想输入的日期和Busno是否与表中的相同然后阻止预订。
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;
tbDate.Text = Calendar1.SelectedDate.ToShortDateString();
using (SqlConnection con = new SqlConnection(cs))
{
string check = "SELECT BusNo, Date FROM Ticket WHERE (BusNo = @busno) AND(Date = @NewDate))";
SqlCommand cmd = new SqlCommand(check, con);
cmd.Parameters.AddWithValue("@busno", tbBusno.Text);
cmd.Parameters.AddWithValue("@NewDate", DateTime.Parse(tbDate.Text));
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (@busno ,@date , @time , @bickup , @dropoff ,@fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("@busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("@date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("@time", tbTime.Text);
cmd2.Parameters.AddWithValue("@dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("@bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("@fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}
}
}
}
答案 0 :(得分:1)
可以尝试删除while (rdr.Read())
部分吗?
因此您的代码将是
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (@busno ,@date , @time , @bickup , @dropoff ,@fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("@busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("@date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("@time", tbTime.Text);
cmd2.Parameters.AddWithValue("@dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("@bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("@fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}