如何使用函数从sqlite数据库中获取数据
本文关键字:获取 数据 数据库 sqlite 何使用 函数 | 更新日期: 2023-09-27 18:17:53
我正在制作Xamarin表单中的应用程序,但无论我尝试什么,我都无法获得sqlite数据库的工作。我想选择所有类别,其中menu_ID = 1我怎么能做到这一点?我需要这个代码在另一个页面(categoripage . example .cs)可以帮助我这个?
下面是我使用的一些代码:(Tables.cs):
namespace AmsterdamTheMapV3
{
public class Categories
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Menu_ID { get; set; }
public string Name { get; set; }
public Categories()
{
}
}
public class Places
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Categorie_ID { get; set; }
public string Name { get; set; }
public Boolean Featured { get; set; }
public string OpenHours { get; set; }
public string Info { get; set; }
public string Images { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Adress { get; set; }
public Places()
{
}
}
public class Events
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public Events()
{
}
}
}
数据库助手(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>();
var categories = new Categories()
{
ID = 1,
Menu_ID = 1,
Name = "test"
};
db.Insert(categories); // Insert the object in the database
}
public IEnumerable<Categories> GetCategories()
{
return (from t in db.Table<Categories>() select t).ToList();
}
//Get specific Categorie
public Categories GetCategorie(int id)
{
return db.Table<Categories>().FirstOrDefault(t => t.ID == id);
}
//Delete specific Categorie
public void DeleteCategorie(int id)
{
db.Delete<Categories>(id);
}
//Add new student to Categorie
public void AddCategorie(Categories categorie)
{
db.Insert(categorie);
}
}
}
CategoriePage.xaml.cs:
public partial class CategoriePage : ContentPage
{
static TheMapDB database;
TheMapDB categorie = new TheMapDB();
public CategoriePage(String txt)
{
InitializeComponent();
var layout = new StackLayout { Padding = new Thickness(5, 10) };
this.Content = layout;
if(txt.Equals("1"))
{
txt = "this text is number 1";
//needed code can't find soluction
}
var label = new Label { Text = txt, TextColor = Color.FromHex("#77d065"), FontSize = 20 };
layout.Children.Add(label);
}
}
提前谢谢你
我建议你用这样的函数创建一个DAO类:(或者把这个函数放在TheMapDB.cs中)
public List<Category> GetCategoryByID(int menuID)
{
return db.Table<Category>().Where(x => x.menu_ID == menuID).ToList();
}
然后您可以在您想要的任何地方调用DAO中的这个函数。对我来说,这似乎是最好的解决办法。当你把这个函数放在TheMapDB.cs类中,你可以在你的categorypage . example .cs中说:
database.GetCategoryByID (menuID);