如何从xamarin中的本地数据库中检索字符串值?

问题描述 投票:1回答:2

表结构

[Table(TableConst.TABLE_BRANDING)]
public class BrandingInfoModel
{
    public int id { get; set; }
    public string title { get; set; }
    public string primary_color { get; set; }
    public string secondary_color { get; set; }
    public string tertiary_color { get; set; }
}

从数据库获取资源的方法

    public string GetColorResourceFromDatabase(string key)
    {
        try
        {

            string value = mSqlConnection.Query<string>("SELECT " + key + " FROM data").ToString();
            return value;

        }
        catch (Exception e)
        {
            string error = e.Message;
            return null;
        }

    }

我编写了基于SELECT查询从本地数据库返回值的方法。但它返回null。

xamarin sqlite-net
2个回答
4
投票

我试过这种方式

  //Get resource from Brading table
    public BrandingInfoModel GetResourceFromDatabase(string key)
    {
        try
        {
            //string value = (from i in mSqlConnection.Table<BrandingInfoModel>() select i.menu_text_color).ToString();

            var queryResult = mSqlConnection.Query<BrandingInfoModel>("SELECT " + key + " FROM " + TableConst.TABLE_BRANDING).FirstOrDefault();
            return queryResult;

        }
        catch (Exception e)
        {
            string error = e.Message;
            return null;
        }

    }

它返回所需的输出。


0
投票

而不是使用SQL查询来执行选择。请考虑使用Linq查询来获得相同的结果。

例如,如果要选择一行并获取带有id的primary_color:

var rowData = mSqlConnection.Table<BrandingInfoModel>()
                            .FirstOrDefault(i => i.id == 123);
if (rowData != null)
{
    return rowData.primary_color;
}
© www.soinside.com 2019 - 2024. All rights reserved.