我遇到了一些sqlite代码的问题,以下函数中的某些内容似乎导致数据库在应该被using语句关闭之后仍然保持打开状态,我可以解决这个问题。在调用函数中调用GC.collect(),但我想尝试找出问题的原因。我已经尝试在使用声明后添加对GC.Collect()的调用,但这似乎不够,因为假设某些内容阻止GC清除?
/// <summary>
/// Gets the Points of Interest for a given Category
/// </summary>
/// <param name="rootPath">Target Path</param>
/// <param name="category">Category to search</param>
/// <returns>A collection of Points of interest</returns>
public static Collection<PointOfInterest> GetPointsOfInterest(string rootPath, PointOfInterestCategory category)
{
if (category == null)
{
throw new ArgumentNullException("category");
}
Collection<PointOfInterest> pointsOfInterest = new Collection<PointOfInterest>();
string databaseLocation = string.Format(Resources.DataFilePath, rootPath, "poidata.db");
using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", databaseLocation)))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(
"SELECT latmin + (latmax - latmin / 2) as lat, lonmin + (lonmax - lonmin / 2) as lon, city, street, housenr, name FROM poicoord JOIN poidata ON poicoord.poiid = poidata.poiid JOIN poiname on poiname.docid = poicoord.poiid WHERE type = @category",
connection))
{
command.Parameters.Add(new SQLiteParameter("category", DbType.Int32) { Value = category.Id });
SQLiteDataReader reader = command.ExecuteReader();
int latOrdinal = reader.GetOrdinal("lat");
int lonOrdinal = reader.GetOrdinal("lon");
int nameOrdinal = reader.GetOrdinal("name");
int houseNrOrdinal = reader.GetOrdinal("housenr");
int streetOrdinal = reader.GetOrdinal("street");
int cityOrdinal = reader.GetOrdinal("city");
while (reader.Read())
{
pointsOfInterest.Add(new PointOfInterest()
{
Latitude = reader.GetDouble(latOrdinal),
Longitude = reader.GetDouble(lonOrdinal),
Name = reader.GetString(nameOrdinal),
HouseNumber = reader.IsDBNull(houseNrOrdinal) ? string.Empty : reader.GetString(houseNrOrdinal),
Street = reader.IsDBNull(streetOrdinal) ? string.Empty : reader.GetString(streetOrdinal),
City = reader.IsDBNull(cityOrdinal) ? string.Empty : reader.GetString(cityOrdinal),
});
}
}
}
return pointsOfInterest;
}
答案 0 :(得分:1)
尝试实现using
语句,而不是仅仅将读者分配给变量:
using (SQLiteDataReader reader=command.ExecuteReader()) {
...
}
或手动关闭阅读器:
reader.Close();