我正在尝试创建一个sqlite数据库,但我无法成功。这个问题的一大问题是我没有收到任何错误。我甚至无法手动创建.db文件,因为它无法找到。我正在使用Xamarin表单,我使用visual studio 2015来编辑我的代码/文件。这是我的代码:
ISQLite接口:
...
public interface ISQLite
{
SQLiteConnection GetConnection();
}
...
数据库帮助程序(称为TheMapDB.cs):
...
public class TheMapDB
{
private SQLiteConnection db;
public TheMapDB()
{
//Getting conection and Creating table
db = DependencyService.Get<ISQLite>().GetConnection();
db.CreateTable<Categories>();
db.CreateTable<Places>();
db.CreateTable<Events>();
}
public void AddCategorie(Categories categorie)
{
db.Insert(categorie);
}
}
...
表(名为Tables.cs的文件):
public class Categories
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Menu_ID { get; set; }
public string Name { get; set; }
public Categories()
{
}
}
android native side(称为SQLite_Android.cs):
[assembly: Dependency(typeof(SQLite_Android))]
namespace AmsterdamTheMapV3.Droid
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.Net.SQLiteConnection GetConnection()
{
var filename = "database.db3";
var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentspath, filename);
var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var connection = new SQLite.Net.SQLiteConnection(platform, path);
return connection;
}
}
}
我如何调用这些函数:
static TheMapDB database;
Categories student = new Categories();
TheMapDB categorie = new TheMapDB();
public HomePage()
{
student.ID = 1;
student.Menu_ID = 2;
student.Name = "peter";
categorie.AddCategorie(student);
NavigationPage.SetHasNavigationBar(this, false);
categorie.GetCategorie(1);
InitializeComponent();
}
我知道这是很多代码,但我不知道问题出在哪里。 如果需要,我可以提供更多信息。 提前谢谢。
答案 0 :(得分:2)
使用SQLiteConnection.CreateFile(filename.sqlite)方法创建文件。
答案 1 :(得分:2)
请替换: -
var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
使用
var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
这可能是文件夹访问的问题。
已编辑: -
同样在创建数据库之前,还请设置一个条件来检查它是否已经创建,否则它将替换数据库。