如何从SQLite表中获取值的总和?

时间:2012-05-09 05:30:49

标签: vb.net sqlite

我正在尝试收集出价并从列中分配平均值

我收到InvalidCast异常:指定的强制转换无效。在TotalSum + =

任何帮助都会得到极大的帮助

Dim sql As String = "SELECT " & Column & " FROM " & Table & " ;"
Dim dt As DataTable = SQLiteDatabase.GetDataTable(sql)
Column = Column.Replace("[", "")
Column = Column.Replace("]", "")
For Each row As DataRow In dt.Rows
    TotalSum += DirectCast(row(Column), Integer)
    Console.WriteLine("Calculating TotalSum {0}", TotalSum.ToString)
Next row

3 个答案:

答案 0 :(得分:1)

最终解决方案就是这个

Dim suma As Double = 0.0R
For Each row As DataRow In dt.Rows
    Dim num As Double = 0R
    Double.TryParse(row(Column).ToString, num)
    suma += num
Next row

列可以在我的应用程序中有效地包含Stings,因为用户可以直接输入SQL。我只使用Double类型,但Integers是一个选项

答案 1 :(得分:0)

检查

int suma = 0;

Dim dc as DataColumn = dt.Columns[0]  //Column to add
For Each row As DataRow In dt.Rows
          suma += int.Parse(row[dc])

问候

答案 2 :(得分:0)

感谢好回复

我的修复

    Try
        TotalSum += Convert.ToInt32(row(Column))
        Console.WriteLine("Calculating TotalSum {0}", TotalSum.ToString)
    Catch
    End Try

尝试添加Catch Block以观察vbNull。我只想要高于0的价值