尝试使用ExecuteScalar <object>从表中检索数据时出错?

时间:2017-12-06 14:30:33

标签: sqlite xamarin xamarin.forms

我有这堂课:

public class BtnCountViews
{
    public int btnCount { get; set; }
    public int views { get; set; }
}

我正在尝试从我的数据库中检索一行的数据:

sql = " AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = db2.ExecuteScalar<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY");

但这是一个例外,说:

System.NotSupportedException: Don't know how to read Japanese.BtnCountViews
at SQLite.SQLiteCommand.ReadCol (SQLitePCL.sqlite3_stmt stmt, 

我试图查看ExecuteScalar,看起来它可能需要一个对象。

有没有人知道它为什么会抛出异常?

此处的参考是CLICKHISTORY表的对象定义:

public class ClickHistory
{
    [PrimaryKey, NotNull]
    public string Yymmdd { get; set; }
    public int DayOfYear { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int BtnACount { get; set; }
    public int BtnBCount { get; set; }
    public int BtnCCount { get; set; }
    public int BtnDCount { get; set; }
    public int Views { get; set; }
}

1 个答案:

答案 0 :(得分:3)

您正在尝试返回BtnCountViews类型,而不是标量值。

通过BtnCountViews

返回预计的Query
var sql = "AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = conn.Query<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY").First();

Log.Debug(TAG, $"{avg.btnCount} : {avg.views}");

或者通过ExecuteScalar

在两个单独的查询中恢复标量
var sql2 = "(AVG (BTNACOUNT + BTNBCOUNT))";
var btnABAvg = conn.ExecuteScalar<int>("SELECT " + sql2 + " FROM CLICKHISTORY");

var sql3 = "(AVG (VIEWS))";
var viewAvg = conn.ExecuteScalar<int>("SELECT " + sql3 + " FROM CLICKHISTORY");

Log.Debug(TAG, $"{btnABAvg} : {viewAvg}");