Android Question add new field to database after publication

doogal

Member
Licensed User
Longtime User
Title says it all.. I have developed an app for my wife, but now she is wanting me to add more information to it. I didn't plan for future update/new information to be added, so my question is; How can I add new fields to an existing database without losing existing data? An online database would be the best way to do this (I think), but I have never done one of these.

Thank you in advance,
doogal
 

beni_feld

Member
Licensed User
Longtime User
How can I add new fields to an existing database without losing existing data? .

I have the same problem. I use the following code:
B4X:
Sub AddColumns
 
    If ColumnExist("MyTable", "NewColumn")=False Then
         SQL1.ExecNonQuery("ALTER TABLE MyTable ADD NewColumn NVARCHAR(20)")
    End If
 
   If ColumnExist(..........
        .......
   End If
 
End Sub
 
 
Sub ColumnExist(Table As String, ColName As String) As Boolean
   Dim Cursor1 As Cursor
   Dim Query As String
 
   Query="SELECT * FROM " & Table & " LIMIT 1"
   Cursor1 = SQL1.ExecQuery(Query)
   For i=0 To Cursor1.ColumnCount - 1
       Cursor1.Position = 0
       If Cursor1.GetColumnName(i)= ColName Then
          Cursor1.close
          Return True
       End If
   Next
   Cursor1.close
   Return False
End Sub

BN
 
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
Since you know the old database's columns' number, you can just read the columnCount and if it's less than the new one's, alter your table by adding the new fields.
 
Upvote 0

Jack Cole

Well-Known Member
Licensed User
Longtime User
Here is how I do it:

B4X:
Sub check_add_field(cf As String, typ As String, table as String)
Dim R, qry As String
    Try
        qry="select " & cf & " from " & table & " LIMIT 1"
        R=sql1.ExecQuerySingleResult(qry)
        Log("CHECKED COLUMN " & cf & " " & R)
    Catch
        qry="ALTER TABLE " & table & " ADD COLUMN " & cf & " " & typ
        sql1.ExecNonQuery(qry)
        Log("ADDED COLUMN " & cf)
    End Try
End Sub
 
Upvote 0

doogal

Member
Licensed User
Longtime User
Thank you all for the quick solutions. This has been troubling me for a long time. Jack your solution worked best in my app Thank you.
 
Upvote 0
Top