【问题标题】:SQLLite - Select bookings between two datesSQLite - 选择两个日期之间的预订
【发布时间】:2020-03-13 19:57:55
【问题描述】:

我正在尝试将 SQLlite 用于使用 Xamarin.Forms 创建的旅馆预订系统。我想搜索给定 ID 和房间类型的两个日期之间存在的预订记录。

// Count number of bookings between these dates at the hostel for the specified room type
int count = App.Database.CheckValidBooking(hostel_ID, hostel_room_type, DPickerFrom.Date, DPickerTo.Date).Count();

public List<PaidBookings> CheckValidBooking(int ID, string type, DateTime period_start, DateTime period_end)
{
    return database.Query<PaidBookings>("SELECT * FROM PaidBookings WHERE ID = ? AND Type = ? AND checkIn >= ? AND checkOut <= ?;", ID, type, period_start, period_end);
}

执行时出现SQL语句出错:

public List<PaidBookings> CheckValidBooking(int ID, string type, DateTime period_start, DateTime period_end)
{
    return database.Query<PaidBookings>("SELECT * FROM PaidBookings WHERE ID = ? AND Type = ? AND checkIn >= ? AND checkOut <= ?;", ID, type, period_start, period_end);
}

System.NullReferenceException:对象引用未设置为对象的实例。

我该如何解决这个问题?谢谢。

【问题讨论】:

标签: c# sql sqlite xamarin.forms


【解决方案1】:

你应该把你的变量放在“你的变量”之间

试试这个:

database.Query<PaidBookings>(String.Format("SELECT * FROM PaidBookings WHERE ID = '{0}' AND Type = '{1}' AND checkIn >= '{2}' AND checkOut <= '{4}';", ID, type, period_start, period_end));

就像@Shawn 提到的那样,这是一种不好的做法,通常你应该使用如下命令参数:

SqlCommand cmd = new SqlCommand();
cmd.CommandText =String.Format("SELECT * FROM PaidBookings WHERE ID = @ID AND Type = @Type AND checkIn >= @checkIn AND checkOut <= @checkOut;");

//  add parameter to command object
cmd.Parameters.Add(new SqlParameter("@ID", yourId));

....

// execut the commend
 cmd.ExecuteNonQuery();

【讨论】:

  • 呃,没有。这会将问号从绑定到值的参数更改为包含问号的字符串文字,这根本不是您想要的。
  • 不,这也很糟糕——将用户提供的值绑定到参数是唯一的方法。尝试将它们直接插入到这样的查询字符串中会导致 sql 注入和其他错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 2017-03-07
  • 2015-07-08
相关资源
最近更新 更多