1.创建MySQL数据库表
CREATE TABLE appointments ( appointmentId int NOT NULL AUTO_INCREMENT, clientId int NOT NULL, start DATETIME NOT NULL, end DATETIME NOT NULL, PRIMARY KEY (appointmentId) );
2.通过在C#中查询MySQL数据库避免预定重叠
public bool preventOverlappingAppointments(DateTime start, DateTime end) { bool isOverlap = false; string query = "SELECT COUNT(*) FROM appointments WHERE start BETWEEN @start AND @end OR end BETWEEN @start AND @end"; using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@start", start); command.Parameters.AddWithValue("@end", end); connection.Open(); int count = Convert.ToInt32(command.ExecuteScalar()); if (count > 0) { isOverlap = true; } connection.Close(); } return isOverlap; }
3.在预定新约之前检查当前时间段内是否有其他预订
private void btnBookAppointment_Click(object sender, EventArgs e) { DateTime start = dtpStart.Value; DateTime end = dtpEnd.Value;
bool isOverlap = preventOverlappingAppointments(start, end); if (isOverlap) { MessageBox.Show("当前时间段已有预订,请选择其他时间", "重叠的预订", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { //插入新的预订到数据库 } }