i like to connect to two database in save server.username and password also same. i spent most of many hours make it work, but i'm fail. Hope someone can give me a some advice.
here is my code of server side:
main:
RDCHandler:
here is RDCConnector:
here is my config.properties
and the client side code:
how can make it work?
please help me, thanks.
here is my code of server side:
main:
B4X:
'Non-UI application (console / server application)
#Region Project Attributes
#CommandLineArgs:
#MergeLibraries: True
#End Region
Sub Process_Globals
Public srvr As Server
Public rdcConnectorA As RDCConnector
Public rdcConnectorB As RDCConnector
Public const VERSION As Float = 2.1
Type DBCommand (Name As String, Parameters() As Object)
Type DBResult (Tag As Object, Columns As Map, Rows As List)
End Sub
Sub AppStart (Args() As String)
srvr.Initialize("")
rdcConnectorA.Initialize
rdcConnectorB.Initialize
srvr.Port = 12345
srvr.AddHandler("/rdc", "RDCHandler", False)
srvr.Start
Log($"jRDC is running (version = $1.2{VERSION}) Port = ${srvr.Port}"$)
StartMessageLoop
End Sub
RDCHandler:
B4X:
Sub Class_Globals
Private connector As RDCConnector
Private connectors As Map = CreateMap("a":Main.rdcConnectorA,"b":Main.rdcConnectorB)
End Sub
Public Sub Initialize
End Sub
Sub Handle(req As ServletRequest, resp As ServletResponse)
Dim start As Long = DateTime.Now
Dim q As String
Dim in As InputStream = req.InputStream
Dim method As String = req.GetParameter("method")
connector=connectors.Get(req.GetParameter("database")) '<==here i get the null value
Dim con As SQL
Try
con = connector.GetConnection
If method = "query2" Then
q = ExecuteQuery2(con, in, resp)
Else if method = "batch2" Then
q = ExecuteBatch2(con, in, resp)
Else
Log("Unknown method: " & method)
resp.SendError(500, "unknown method")
End If
Catch
Log(LastException)
resp.SendError(500, LastException.Message)
End Try
If con <> Null And con.IsInitialized Then con.Close
Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$)
End Sub
Private Sub ExecuteQuery2 (con As SQL, in As InputStream, resp As ServletResponse) As String
Dim ser As B4XSerializator
Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in))
Dim cmd As DBCommand = m.Get("command")
Dim limit As Int = m.Get("limit")
Dim rs As ResultSet = con.ExecQuery2(connector.GetCommand(cmd.Name), cmd.Parameters)
If limit <= 0 Then limit = 0x7fffffff 'max int
Dim jrs As JavaObject = rs
Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null)
Dim cols As Int = rs.ColumnCount
Dim res As DBResult
res.Initialize
res.columns.Initialize
res.Tag = Null 'without this the Tag properly will not be serializable.
For i = 0 To cols - 1
res.columns.Put(rs.GetColumnName(i), i)
Next
res.Rows.Initialize
Do While rs.NextRow And limit > 0
Dim row(cols) As Object
For i = 0 To cols - 1
Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1))
'check whether it is a blob field
If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then
row(i) = rs.GetBlob2(i)
Else if ct = 2 Or ct = 3 Then
row(i) = rs.GetDouble2(i)
Else
row(i) = jrs.RunMethod("getObject", Array(i + 1))
End If
Next
res.Rows.Add(row)
Loop
rs.Close
Dim data() As Byte = ser.ConvertObjectToBytes(res)
resp.OutputStream.WriteBytes(data, 0, data.Length)
Return "query: " & cmd.Name
End Sub
Private Sub ExecuteBatch2(con As SQL, in As InputStream, resp As ServletResponse) As String
Dim ser As B4XSerializator
Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in))
Dim commands As List = m.Get("commands")
Dim res As DBResult
res.Initialize
res.columns = CreateMap("AffectedRows (N/A)": 0)
res.Rows.Initialize
res.Tag = Null
Try
con.BeginTransaction
For Each cmd As DBCommand In commands
con.ExecNonQuery2(connector.GetCommand(cmd.Name), _
cmd.Parameters)
Next
res.Rows.Add(Array As Object(0))
con.TransactionSuccessful
Catch
con.Rollback
Log(LastException)
resp.SendError(500, LastException.Message)
End Try
Dim data() As Byte = ser.ConvertObjectToBytes(res)
resp.OutputStream.WriteBytes(data, 0, data.Length)
Return $"batch (size=${commands.Size})"$
End Sub
here is RDCConnector:
B4X:
Sub Class_Globals
Private pool As ConnectionPool
Private DebugQueries As Boolean
Private commands As Map
Public serverPort As Int
End Sub
'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
Dim config As Map = LoadConfigMap
pool.Initialize(config.Get("DriverClass1"), config.Get("JdbcUrl1"), config.Get("User1"), _
config.Get("Password1"))
#if DEBUG
DebugQueries = True
#else
DebugQueries = False
#end if
serverPort = config.Get("ServerPort")
LoadSQLCommands(config)
End Sub
Private Sub LoadConfigMap As Map
Return File.ReadMap(File.DirAssets, "config.properties")
End Sub
Public Sub GetCommand(Key As String) As String
If commands.ContainsKey("sql." & Key) = False Then
Log("*** Command not found: " & Key)
End If
Return commands.Get("sql." & Key)
End Sub
Public Sub GetConnection As SQL
If DebugQueries Then LoadSQLCommands(LoadConfigMap)
Return pool.GetConnection
End Sub
Private Sub LoadSQLCommands(config As Map)
Dim newCommands As Map
newCommands.Initialize
For Each k As String In config.Keys
If k.StartsWith("sql.") Then
newCommands.Put(k, config.Get(k))
End If
Next
commands = newCommands
End Sub
here is my config.properties
B4X:
#Lines starting with '#' are comments.
#Backslash character at the end of line means that the command continues in the next line.
#DATABASE CONFIGURATION
DriverClass1=com.mysql.jdbc.Driver
JdbcUrl1=jdbc:mysql://localhost:12345/data1?useSSL=false
User1=user1
Password1=pass1
DriverClass2=com.mysql.jdbc.Driver
JdbcUrl2=jdbc:mysql://localhost:12345/data2?useSSL=false
User2=user1
Password2=pass1
#Java server port
ServerPort=19980
#example of MS SQL Server configuration:
#DriverClass=net.sourceforge.jtds.jdbc.Driver
#JdbcUrl=jdbc:jtds:sqlserver://<server address>/<database>
#example of postegres configuration:
#JdbcUrl=jdbc:postgresql://localhost/test
#DriverClass=org.postgresql.Driver
#SQL COMMANDS
sql.select_checking_internet=SELECT value FROM tbl_internet_checking
and the client side code:
B4X:
Public Sub ExecuteQuery(Command As DBCommand, Limit As Int, Tag As Object,database As String)
Dim ser As B4XSerializator
Dim data() As Byte = ser.ConvertObjectToBytes(CreateMap("command": Command, "limit": Limit, "version": VERSION))
SendJob(data, Tag, "query2",database)
End Sub
Private Sub SendJob(Data() As Byte, Tag As Object, Method As String,database As String)
Dim j As HttpJob
j.Initialize("DBRequest", mTarget)
j.Tag = Tag
j.PostBytes(link & "?method=" & Method & "&database=" & database, Data)
End Sub
how can make it work?
please help me, thanks.