Android Code Snippet DBUtils: clear table (delete all)

Discussion in 'Code Snippets' started by peacemaker, Nov 7, 2018.

  1. peacemaker

    peacemaker Well-Known Member Licensed User

    Code:
    'Tests whether the given table exists
    Public Sub TableExists(SQL As SQL, TableName As StringAs Boolean
        
    Dim count As Int = SQL.ExecQuerySingleResult2("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? COLLATE NOCASE"Array As String(TableName))
        
    Return count > 0
    End Sub

    'Deletes all the records of a table
    Public Sub ClearTable(SQL As SQL, TableName As String)
        
    If TableExists(SQL, TableName) = False Then
            
    Return
        
    End If
        
    SQL.ExecNonQuery("DELETE FROM " & TableName)
    End Sub
     
    Last edited: Nov 7, 2018
    Star-Dust, Erel and MarcoRome like this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    Two comments:

    - Not all code paths return a value.
    - Utility methods or library methods should avoid catching errors (in most cases).
     
    peacemaker likes this.
  3. peacemaker

    peacemaker Well-Known Member Licensed User

    Thanks, Erel, but how to make sure that SQL's NonQuery is done without error ?
     
  4. DonManfred

    DonManfred Expert Licensed User

    Use a non query batch and wait for the result.
    Code:
    For i = 1 To 1000
      
    sql.AddNonQueryToBatch("INSERT INTO table1 VALUES (?)"Array(Rnd(0100000)))
    Next
    Dim SenderFilter As Object = sql.ExecNonQueryBatch("SQL")
    Wait For (SenderFilter) SQL_NonQueryComplete (Success As Boolean)
    Log("NonQuery: " & Success)
     
  5. peacemaker

    peacemaker Well-Known Member Licensed User

    DBUtils is a code module. That does not handle events...
     
  6. DonManfred

    DonManfred Expert Licensed User

    You can use the code in a activity or a service. No need to use it inside dbutils
     
  7. Erel

    Erel Administrator Staff Member Licensed User

    If the SQL command raised an error then there is a programming mistake that should be fixed. In most cases it is better not to hide the error and let the developer, who is using the code you posted, handle the error in any way they like.
     
    peacemaker likes this.
  8. peacemaker

    peacemaker Well-Known Member Licensed User

    OK, thanks, the 1st post is edited.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice