C# 使用sqlite从数据库中选择字符串值
我有个问题。我正在尝试从数据库中获取一个值(字符串)。以下是我调用以获取值的代码:C# 使用sqlite从数据库中选择字符串值,c#,sqlite,xamarin.android,android-sqlite,C#,Sqlite,Xamarin.android,Android Sqlite,我有个问题。我正在尝试从数据库中获取一个值(字符串)。以下是我调用以获取值的代码: public string SelectValueFromTableSettings(string name) { string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); try { using (var connection = new SQL
public string SelectValueFromTableSettings(string name)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT Value FROM SettingDb WHERE Name=?", name).ToString();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
我应该得到一个像Nick或Steve一样的值,但我得到的值是:
系统.集合.通用.列表'1[加密货币.设置数据库]
我做错了什么?您正在返回一个对象列表
connection.Query<SettingDb>("SELECT Value FROM SettingDb WHERE Name=?", name).FirstOrDefault().YourProperty.ToString();
connection.Query(“从SettingDb中选择值,其中Name=?”,Name).FirstOrDefault().YourProperty.ToString();
或者,只需返回对象:
public SettingDB SelectValueFromTableSettings(string name)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT Value FROM SettingDb WHERE Name=?", name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
public SettingDB SelectValueFromTableSettings(字符串名称)
{
string folder=System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
尝试
{
使用(var connection=newsqliteconnection(System.IO.Path.Combine(文件夹,“Settings.db”))
{
返回connection.Query(“从SettingDb中选择值,其中Name=?”,Name).FirstOrDefault();
}
}
catch(SQLiteException-ex)
{
Log.Info(“SQLiteEx”,ex.Message);
返回null;
}
}
然后访问所需的属性。不是枚举连接.查询(“…”)的结果,而是对其调用
ToString()
connection.Query()
返回List
。因为对List
没有合理的字符串化,所以它只有默认的ToString()
,返回GetType().FullName
或其他内容。相反,在列表中循环。然后我应该做什么?在查询返回的列表中循环。查看其中是否有任何内容。当您对查询结果调用ToString()
时,您将获得结果类的名称,这是一个设置列表。对列表中的第一个数据使用FirstOrDefault()
而不是ToString()
,并使用SettingDb属性获得所需的结果。是否请发布SettingsDb类。谢谢,这对我帮助很大
public SettingDB SelectValueFromTableSettings(string name)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT Value FROM SettingDb WHERE Name=?", name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}