I researched several tutorials and posts here on the forum, but I still have questions about best practices for accessing a remote database.
I have in mind an UI application that will be open for hours, sending intermittent reads and writes.
My doubts:
I have in mind an UI application that will be open for hours, sending intermittent reads and writes.
My doubts:
- Use GetConnection and ClosePool only once?
- GetConnection once in AppStart and ClosePool once in CloseRequest?
- Can the WriteData and ReadData procedures be improved?
Sample Code:
#Region Project Attributes
#MainFormWidth: 600
#MainFormHeight: 600
#AdditionalJar: mysql-connector-java-5.1.48.jar
#End Region
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Dim pool As ConnectionPool
#Region Database Location
Private DBLocation As String = "999.999.999.99:3306"
Private DBname As String = "dbname"
Private DBUsername As String = "dbusername"
Private DBPassword As String = "dbpassword"
#End Region
Private sq As SQL
Private t As Timer, op As Int
End Sub
Sub AppStart (Form1 As Form, Args() As String)
MainForm.Initialize("Form", 300,300)
'MainForm = Form1
'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
MainForm.Show
pool.Initialize("com.mysql.jdbc.Driver", $"jdbc:mysql://${DBLocation}/${DBname}?characterEncoding=utf8"$, DBUsername, DBPassword)
t.Initialize("t", Rnd(1000, 6 * 1000))
t.Enabled = True
End Sub
Sub t_tick
LogError("tick " & DateTime.Time(DateTime.Now))
t.Enabled = False
If op = 0 Then
op = 1
ReadData
Else
WriteData
op = 0
End If
't.Interval = Rnd(1000, 60 * 1000)
t.Interval = Rnd(1000, 6 * 1000)
t.Enabled = True
End Sub
Sub WriteData
sq = pool.GetConnection
sq.BeginTransaction
sq.ExecNonQuery("UPDATE config_cfg SET cfg_value = 'SP' WHERE cfg_id = 1006")
sq.TransactionSuccessful
sq.Close
Log("WRITE OK " & DateTime.Time(DateTime.Now))
End Sub
Sub ReadData
sq = pool.GetConnection
Dim Cursor As ResultSet
Cursor = sq.ExecQuery("SELECT cfg_id, cfg_name FROM config_cfg LIMIT 2")
Do While Cursor.NextRow
Log(Cursor.GetString("cfg_id"))
Log(Cursor.Getstring("cfg_name"))
Loop
Cursor.Close
sq.Close
Log("READ OK " & DateTime.Time(DateTime.Now))
End Sub
Private Sub Form_Closed()
Log("Leaving...")
pool.ClosePool
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
Last edited: