我正在尝试从这篇文章中适应VB.NET最常见答案的代码:
Sqlite Check if Table is Empty
原始代码是
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
我的代码看起来像('仅在屏幕上显示消息,我将在稍后填写If - Else代码')
Using conn As New SQLiteConnection("Data Source=myDataBase.sqlite;Version=3;foreign keys=true")
Try
conn.Open()
Dim emptyUserTable = "SELECT COUNT(*) FROM usersTable"
Dim cmdIsEmpty As SQLiteCommand = New SQLiteCommand(emptyUserTable, conn)
Try
Dim Answer As Integer
Answer = cmdIsEmpty.ExecuteNonQuery()
MsgBox(Answer)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
但是“答案”总是-1,空表还是没有。
我不知道如何使用getWritableDataBase,因为我得到了一个 getWritableDatabase不是SQLiteConnection的成员
与rawQuery相同。
如何在VB.NET上检查usersTable是否为空?
答案 0 :(得分:1)
我已经抽象了一些代码,因此它可以用于任何表:
Private Function IsTableEmpty(tblName As String) As Boolean
Dim sql = String.Format("SELECT COUNT(*) FROM {0}", tblName)
Using conn As New SQLiteConnection(LiteConnStr)
Using cmd As New SQLiteCommand(sql, conn)
conn.Open()
Dim rows = Convert.ToInt32(cmd.ExecuteScalar())
Return rows = 0
End Using
End Using
End Function
用法:
If IsTableEmpty("usersTable") Then
Console.Beep()
End If
注释
ExecuteScalar()
获取倒计时,然后测试0行