After (unfortunately) having write many functions (in a code module in my b4j server project) which access a MySql, I remembered a fundamental rule: use Try-Catch when accessing external resources.
So I thought to change all the functions that access the DB (and unfortunately all the calls to these functions, throughout the project) by imitating what we do in the Jobdone (http query): verify first of all the "Success" of the query; but how?
To do so, I create a Type in my DB queries module:
Now, all my DB functions will return mDBResult.
No more:
but now:
Obviously now calling a function like this requires writing more lines.
Before:
Now:
but whis way you can handle db access errors and avoid app (server!) crashes!
I think I will try to implement other: run the query(s) a second time, before returning Success = False (this requires to use recursive functions; I do not know if I want to work so much ).
[P.S.] It would also be useful if tDBResult also contained the error message; still better a constant (enum ) that indicates the error type.
So I thought to change all the functions that access the DB (and unfortunately all the calls to these functions, throughout the project) by imitating what we do in the Jobdone (http query): verify first of all the "Success" of the query; but how?
To do so, I create a Type in my DB queries module:
B4X:
' modDB - code module
Sub Process_Globals
Type tDBResult(Success As Boolean, ResultData As Object)
Private mDBResult As tDBResult
' ...
End Sub
Sub Init ' to be called once, as if this were a class module.
mDBResult.Initialize
End Sub
Now, all my DB functions will return mDBResult.
No more:
B4X:
Sub GetUserID(UserName As String, PW As String) As Int
Dim UserId As Int = - 1 ' = not found.
' query execution
Return UserID
End Sub
B4X:
Sub GetUserID(UserName As String, PW As String) As tDBResult
mDBResult.Success = True
Dim UserId As Int = - 1 ' not found.
Try
' query execution
UserId = ...
mDBResult.ResultaData = UserID
Catch
mDBResult.Success = False
End Try
Return mDBResult
End Sub
Obviously now calling a function like this requires writing more lines.
Before:
B4X:
Dim UserID = modDB.GetUserID("Erel", "NamesOfMyFourQueens") ' this is his real password ^__^
B4X:
' Module variable.
Private mDBResult As tDBResult
' In Activity_Create of where you need it.
mDBResult.Initialize
' In your routine.
Dim UserID
mDBResult = modDB.GetUserID("Erel", "NamesOfMyFourQueens")
If mDBResult.Success Then
UserID = mDBResult.ResultData
Else
' handle the error.
End If
but whis way you can handle db access errors and avoid app (server!) crashes!
I think I will try to implement other: run the query(s) a second time, before returning Success = False (this requires to use recursive functions; I do not know if I want to work so much ).
[P.S.] It would also be useful if tDBResult also contained the error message; still better a constant (enum ) that indicates the error type.
Last edited: