B4J Question [SOLVED] Best Practices for Local MySQL Usage in B4J Projects

jroriz

Active Member
Licensed User
Longtime User
I'm starting a new B4J project on a local network using MySQL. I've reviewed several posts on this forum about MySQL, particularly regarding connection handling.
I’d like to know the best practices for using MySQL locally.

So far, I have this code:
B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600

    #AdditionalJar: mysql-connector-java-5.1.27-bin.jar

#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Public TabPane1 As TabPane
    Private txtSenha As TextField
    Private lblTit As Label
    Private lblVersao As Label
    Private XUI As XUI
    Private txtUsuario As campo

    Dim MySQL As SQL

End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Login")

    lblTit.Text = "JTicketPRO - Controle de Gratuidade em Coletivos"
    
    lblVersao.Text = "versão 1.0.0"
    
    MainForm.Show
End Sub

'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Private Sub btnEntrar_Click
    MySQL.Initialize2("com.mysql.jdbc.Driver", "jdbc:mysql://192.168.0.202/ticketpro?characterEncoding=utf8", txtCampo.text, txtSenha.text)
    
    XUI.MsgboxAsync("Bem-vindo", "")

End Sub
Is there anything that could be improved in this code?

One question I have: Let's say I have a CRUD form. Should I open the connection on form load and close it when the form closes, or should I open and close the connection each time I perform a database operation?



 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Consider using ConnectionPool: jConnectionPool - ConnectionPool extracted from jServer
The advantage in this case is that you will (almost) not need to worry about the connection state. Get a "new" connection from the db just before you need it and "close" it once done. You do need to do it correctly and close the connection in all cases as to not leak connections.

Without ConnectionPool you will need to handle the connection yourself and opening it when the form is opened is a good solution. Don't assume that a connection will stay alive forever.
 
Upvote 0
Top