Android Question Best Connection with SQL Server 2022 Express?

jeronimovilar

Active Member
Licensed User
Longtime User
How the best conection (fast and security) with Sql Server 2022 Express (windows)? I tryed JDBC (mssql-jdbc), but not connect :(
My MS SQL SERVER and Android App are in Intranet (192.168.0.xxx)
 

Chris2

Active Member
Licensed User
Longtime User
Have a look at jRDC2, which requires you to create a middleware server app (there are lots of project templates and examples in the forum).
If you prefer a direct database connection, look at the jdbcSQL tutorial.

I tryed JDBC (mssql-jdbc), but not connect :(
You'll need to post your connection code and the error messages in the logs if you expect people to be able to help with this.
 
Upvote 1

jeronimovilar

Active Member
Licensed User
Longtime User
My code:

B4X:
#Region  Project Attributes
    #ApplicationLabel: Teste Extremo SQL
    #VersionCode: 1
    #VersionName: 1.0
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    '#AdditionalJar: mssql-jdbc-9.4.1.jre11.jar
    #AdditionalJar: mssql-jdbc-12.8.1.jre8.jar
#End Region

Sub Process_Globals
    Public sql As JdbcSQL
    Private driver As String = "com.microsoft.sqlserver.jdbc.SQLServerDriver"   
    Private testeEmAndamento As Boolean = False
    Private tentativa As Int = 1
End Sub

Sub Globals
    Private txtIP, txtPorta As EditText
    Private btnTestar, btnDiagnostico As Button
    Private lblStatus, lblDetalhes As Label
    Private ProgressBar1 As ProgressBar
    Private pnlConfig As Panel
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Log("Iniciando aplicação...")
    Log("JAR SQL Server: mssql-jdbc-12.8.1.jre8.jar")
    
    Try
        ' Tenta carregar uma classe do driver para verificar
        Dim jo As JavaObject
        jo.InitializeStatic("com.microsoft.sqlserver.jdbc.SQLServerDriver")
        Log("Driver SQL Server OK!")
    Catch
        Log("ERRO: Não foi possível carregar o driver SQL Server")
        Log("Verifique se o JAR está em #AdditionalJar")
    End Try
    
    Activity.Color = Colors.White
    CriarLayoutExtremo
    
    txtIP.Text = "10.80.167.56"    ' "192.168.68.101"
    txtPorta.Text = "1434"
End Sub

Sub CriarLayoutExtremo
    Dim largura As Int = 100%x
    Dim margem As Int = 15dip
    Dim alturaItem As Int = 45dip
    Dim topo As Int = 20dip
    
    ' Painel
    pnlConfig.Initialize("")
    Activity.AddView(pnlConfig, 0, 0, largura, 100%y)
    pnlConfig.Color = Colors.White
    
    ' Título
    Dim lblTitulo As Label
    lblTitulo.Initialize("")
    pnlConfig.AddView(lblTitulo, 0, topo, largura, 40dip)
    lblTitulo.Text = "CONEXÃO EXTREMA SQL 2022"
    lblTitulo.TextSize = 16
    lblTitulo.Gravity = Gravity.CENTER
    lblTitulo.TextColor = Colors.Red
    topo = topo + 50dip
    
    ' IP
    Dim lblIP As Label
    lblIP.Initialize("")
    pnlConfig.AddView(lblIP, margem, topo, largura - 2*margem, 20dip)
    lblIP.Text = "IP do SQL Server 2022:"
    lblIP.TextSize = 12
    topo = topo + 25dip
    
    txtIP.Initialize("")
    pnlConfig.AddView(txtIP, margem, topo, largura - 2*margem, alturaItem)
    txtIP.Text = "192.168.68.101"
    topo = topo + alturaItem + 10dip
    
    ' Porta
    Dim lblPorta As Label
    lblPorta.Initialize("")
    pnlConfig.AddView(lblPorta, margem, topo, largura - 2*margem, 20dip)
    lblPorta.Text = "Porta TCP (1434):"
    lblPorta.TextSize = 12
    topo = topo + 25dip
    
    txtPorta.Initialize("")
    pnlConfig.AddView(txtPorta, margem, topo, 100dip, alturaItem)
    txtPorta.Text = "1434"
    topo = topo + alturaItem + 20dip
    
    ' Botões
    btnDiagnostico.Initialize("btnDiagnostico")
    pnlConfig.AddView(btnDiagnostico, margem, topo, (largura - 3*margem)/2, alturaItem)
    btnDiagnostico.Text = "TESTAR PORTA"
    btnDiagnostico.Color = Colors.Yellow
    
    btnTestar.Initialize("btnTestar")
    pnlConfig.AddView(btnTestar, 2*margem + (largura - 3*margem)/2, topo, (largura - 3*margem)/2, alturaItem)
    btnTestar.Text = "TESTE EXTREMO"
    btnTestar.Color = Colors.Red
    topo = topo + alturaItem + 20dip
    
    ' ProgressBar
    ProgressBar1.Initialize("")
    pnlConfig.AddView(ProgressBar1, margem, topo, largura - 2*margem, 15dip)
    ProgressBar1.Visible = False
    topo = topo + 25dip
    
    ' Status
    lblStatus.Initialize("")
    pnlConfig.AddView(lblStatus, margem, topo, largura - 2*margem, 50dip)
    lblStatus.Gravity = Gravity.CENTER
    lblStatus.TextSize = 16
    lblStatus.Text = "MODO EXTREMO ATIVADO"
    lblStatus.TextColor = Colors.Red
    topo = topo + 60dip
    
    ' Detalhes
    lblDetalhes.Initialize("")
    pnlConfig.AddView(lblDetalhes, margem, topo, largura - 2*margem, 300dip)
    lblDetalhes.TextSize = 11
    lblDetalhes.TextColor = Colors.DarkGray
    lblDetalhes.Text = "CONFIGURAÇÃO RADICAL SQL 2022:" & CRLF & _
                      "1. ForceEncryption: DISABLED" & CRLF & _
                      "2. TLS/SSL: DISABLED" & CRLF & _
                      "3. Protocolo: TCP apenas" & CRLF & _
                      "4. Compatibilidade: 2019" & CRLF & _
                      "5. Login: sa / surfbyte" & CRLF & _
                      "6. Banco: master" & CRLF & CRLF & _
                      "Executando 5 métodos extremos..."
End Sub

Sub btnDiagnostico_Click
    Dim ip As String = txtIP.Text.Trim
    If ip = "" Then ip = "10.80.167.56"
    
    Dim porta As String = txtPorta.Text.Trim
    If porta = "" Then porta = "1434"
    
    ProgressBar1.Visible = True
    lblStatus.Text = "Testando porta..."
    lblStatus.Color = Colors.Blue
    
    Dim resultado As String = TestarPorta(ip, porta)
    
    ProgressBar1.Visible = False
    
    If resultado = "OK" Then
        lblStatus.Text = "PORTA ABERTA"
        lblStatus.Color = Colors.Green
        lblDetalhes.Text = "Port " & porta & " OK!" & CRLF & _
                          "Server: " & ip & CRLF & _
                          "Ready for test."
    Else
        lblStatus.Text = "PORTA FECHADA"
        lblStatus.Color = Colors.Red
        lblDetalhes.Text = "Porta " & porta & " not ready." & CRLF & _
                          "ERRO: " & resultado & CRLF & CRLF & _
                          ""
    End If
    
    Log(DateTime.Time(DateTime.Now) & ": " & lblDetalhes.Text)
    Log(DateTime.Time(DateTime.Now) & ": " & lblStatus.Text)
End Sub

Sub TestarPorta(host As String, port As String) As String
    Try
        Dim portaInt As Int = port
        
        Dim socket As JavaObject
        socket.InitializeNewInstance("java.net.Socket", Null)
        
        Dim inetAddress As JavaObject
        inetAddress.InitializeStatic("java.net.InetAddress")
        Dim addr As JavaObject = inetAddress.RunMethod("getByName", Array(host))
        
        Dim socketAddress As JavaObject
        socketAddress.InitializeNewInstance("java.net.InetSocketAddress", Array(addr, portaInt))
        
        socket.RunMethod("connect", Array(socketAddress, 5000))
        
        Dim conectado As Boolean = socket.RunMethod("isConnected", Null)
        
        If conectado Then
            socket.RunMethod("close", Null)
            Return "OK"
        Else
            Return "Não conectado"
        End If
        
    Catch
        Return LastException.Message
    End Try
End Sub

Sub btnTestar_Click
    If testeEmAndamento Then Return
    
    Dim ipServidor As String = txtIP.Text.Trim
    Dim porta As String = txtPorta.Text.Trim
    
    If ipServidor = "" Then ipServidor = "192.168.68.101"
    If porta = "" Then porta = "1434"
    
    tentativa = 1
    testeEmAndamento = True
    btnTestar.Enabled = False
    btnDiagnostico.Enabled = False
    ProgressBar1.Visible = True
    
    ExecutarTesteExtremo(ipServidor, porta, 1)
End Sub

Sub ExecutarTesteExtremo(ipServidor As String, porta As String, metodo As Int)
    
    Dim url As String
    Dim usuario As String = "sa"
    Dim senha As String = "surfbyte"
    Dim banco As String = "SurfByte"
    
            ' MÉTODO 1: Forçar TLS 1.0 desabilitado COMPLETAMENTE
            url = "jdbc:sqlserver://" & ipServidor & ":" & porta & ";" & _
                  "databaseName=" & banco & ";" & _
                  "instance=SQLEXPRESS;" & _
                  "user=" & usuario & ";" & _
                  "password=" & senha & ";" & _                 
                  "encrypt=false;" & _
                  "trustServerCertificate=false;" & _
                  "loginTimeout=30;" & _
                  "sendStringParametersAsUnicode=true;" & _
                  "integratedSecurity=false;" & _
                  "authenticationScheme=NTLM;" & _
                  "jaasConfigurationName=SQLJDBCDriver;" & _
                  "trustStore=;" & _
                  "trustStorePassword=;" & _
                  "hostNameInCertificate=*;" & _
                  "serverNameAsACE=false;" & _
                  "xopenStates=false;" & _
                  "sendTimeAsDatetime=true;" & _
                  "packetSize=4096;" & _
                  "multiSubnetFailover=false"
            lblStatus.Text = "MÉTODO 1: TLS DESABILITADO"
            
    
    lblDetalhes.Text = "Método " & metodo & " de 5" & CRLF & _
                      "URL: " & url & CRLF & _
                      "Timeout: 30 segundos"
    
    Log(DateTime.Time(DateTime.Now) & ": " & "=== Starting... ===")
    Log(DateTime.Time(DateTime.Now) & ": " & "URL: " & url)
    
    If sql.IsInitialized Then sql.Close
    
    Try
        If url.Contains("user=") Then
            sql.InitializeAsync("SQL", driver, url, "", "")
        Else
            sql.InitializeAsync("SQL", driver, url, usuario, senha)
        End If
        
        Log(DateTime.Time(DateTime.Now) & ": " & "url  Start")
        
        ' Timeout longo
        Dim inicio As Long = DateTime.Now
        Do While DateTime.Now < inicio + 30000 And testeEmAndamento
            Sleep(100)
        Loop
        
        
    Catch
        Log(DateTime.Time(DateTime.Now) & ": " & "Error: " & LastException.Message)
'        ExecutarTesteExtremo(ipServidor, porta, metodo + 1)
    End Try
End Sub

Sub SQL_Ready (Success As Boolean)
    Log(DateTime.Time(DateTime.Now) & ": " & "SQL_Ready: " & Success)
    
    If Success Then
        ' CONSEGUIMOS!
        Try
            Dim cur As JdbcResultSet = sql.ExecQuery("SELECT @@VERSION as versao")
            
            If cur.NextRow Then
                Dim versao As String = cur.GetString("versao")
                cur.Close
                
                Dim versaoCurta As String = versao
                If versao.Length > 40 Then
                    versaoCurta = versao.SubString2(0, 40) & "..."
                End If
                
                FinalizarTeste(True, "SUCESSO NO MÉTODO " & tentativa & "!" & CRLF & CRLF & _
                             "SQL SERVER 2022 CONECTADO!" & CRLF & _
                             "Versão: " & versaoCurta & CRLF & CRLF & _
                             "Configuração que funcionou:" & CRLF & _
                             lblStatus.Text)
            Else
                cur.Close
                FinalizarTeste(True, "CONECTADO! Método " & tentativa)
            End If
            
        Catch
            FinalizarTeste(True, "CONECTADO! Erro consulta:" & CRLF & _
                         LastException.Message)
        End Try
    Else
        ' Falha - próximo método
        Dim erro As String = LastException.Message
        Log(DateTime.Time(DateTime.Now) & ": " & "Fail " & tentativa & ": " & erro)
        
        Dim ipServidor As String = txtIP.Text.Trim
        Dim porta As String = txtPorta.Text.Trim
        
        'ExecutarTesteExtremo(ipServidor, porta, tentativa + 1)
    End If
End Sub

Sub FinalizarTeste(sucesso As Boolean, mensagem As String)
    testeEmAndamento = False
    btnTestar.Enabled = True
    btnDiagnostico.Enabled = True
    ProgressBar1.Visible = False
    
    If sucesso Then
        lblStatus.Text = "CONEXÃO EXTREMA OK!"
        lblStatus.Color = Colors.Green
    Else
        lblStatus.Text = "FALHA TOTAL"
        lblStatus.Color = Colors.Red
    End If
    
    lblDetalhes.Text = mensagem
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If sql.IsInitialized Then
        sql.Close
    End If
End Sub

LOG:

Iniciando aplicação...
JAR SQL Server: mssql-jdbc-12.8.1.jre8.jar
Driver SQL Server OK!
09:28:27: Port 1434 OK!
Server: 10.80.167.56
Ready for test.
09:28:27: PORTA ABERTA
09:28:27: === Starting... ===
09:28:27: URL: jdbc:sqlserver://10.80.167.56:1434;databaseName=SurfByte;instance=SQLEXPRESS;user=sa;password=surfbyte;encrypt=false;trustServerCertificate=false;loginTimeout=30;sendStringParametersAsUnicode=true;integratedSecurity=false;authenticationScheme=NTLM;jaasConfigurationName=SQLJDBCDriver;trustStore=;trustStorePassword=;hostNameInCertificate=*;serverNameAsACE=false;xopenStates=false;sendTimeAsDatetime=true;packetSize=4096;multiSubnetFailover=false
09:28:27: url Start
09:30:24: SQL_Ready: false
09:30:24: Fail 1: java.io.IOException: Connection reset ClientConnectionId:daa38001-ab71-4ac1-b439-af4ed4a3e94c
 
Upvote 0

Alex_197

Well-Known Member
Licensed User
Longtime User
In my project I have a website (ASP.NET) where I created a page that takes requests from the app, does all the jobs and returns JSON to the app,
 
Upvote 0

QSerg

Member
How the best conection (fast and security) with Sql Server 2022 Express (windows)? I tryed JDBC (mssql-jdbc), but not connect :(
My MS SQL SERVER and Android App are in Intranet (192.168.0.xxx)
I have tried everything that I could find. All solutions are cumbersome and plainly ugly. I finished up with creation of service that runs on SQL computer and I communicate with this service from Android via TCP/IP. Sounds complicated, but in reality you need to create few functions from both sides and after that it became a breeze. I create scanning application in production environment and it running for few years without any problems. Write me back if you need more details.
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
I recommend to check my creation:


 
Last edited:
Upvote 0

aeric

Expert
Licensed User
Longtime User
Personally I don't use jRDC2 and MS SQL Express.

However, I have my own B4J Web API Server which can connect to MS SQL Server or SQL Express.
This is my preferred way.

My Support Ticketing System is a good example of project capable of connecting to multiple types of database.
 
Upvote 0

Chris2

Active Member
Licensed User
Longtime User
Iniciando aplicação...
JAR SQL Server: mssql-jdbc-12.8.1.jre8.jar
Driver SQL Server OK!
09:28:27: Port 1434 OK!
Server: 10.80.167.56
Ready for test.
09:28:27: PORTA ABERTA
09:28:27: === Starting... ===
09:28:27: URL: jdbc:sqlserver://10.80.167.56:1434;databaseName=SurfByte;instance=SQLEXPRESS;user=sa;password=surfbyte;encrypt=false;trustServerCertificate=false;loginTimeout=30;sendStringParametersAsUnicode=true;integratedSecurity=false;authenticationScheme=NTLM;jaasConfigurationName=SQLJDBCDriver;trustStore=;trustStorePassword=;hostNameInCertificate=*;serverNameAsACE=false;xopenStates=false;sendTimeAsDatetime=true;packetSize=4096;multiSubnetFailover=false
09:28:27: url Start
09:30:24: SQL_Ready: false
09:30:24: Fail 1: java.io.IOException: Connection reset ClientConnectionId:daa38001-ab71-4ac1-b439-af4ed4a3e94c
I also think there's at least one thing wrong in your jdbc connection url.
According to this, when using NTLM Autentication you must also have integratedSecurity=true.
 
Upvote 0

jeronimovilar

Active Member
Licensed User
Longtime User
I also think there's at least one thing wrong in your jdbc connection url.
According to this, when using NTLM Autentication you must also have integratedSecurity=true.
I´d tried with:
"encrypt=false;"
"encrypt=true;"
"trustServerCertificate=false;"
"trustServerCertificate=true;"
....
not work
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Check:
Page 7: Alternative login with Windows Authentication
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
The general format for a SQL Server 2022 Express JDBC connection string is jdbc:sqlserver://[serverName\instanceName][:portNumber];[property=value[;property=value]]. Specific examples vary based on the authentication method and server configuration:

Using Windows Authentication (Integrated Security)
This is common for local development when running your Java application on a Windows machine within the same domain as the SQL Server instance.
  • To a named instance (e.g., SQLEXPRESS) on the local machine:
    String connectionUrl = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=MyDatabase;integratedSecurity=true;encrypt=true;trustServerCertificate=true";
  • To the default instance on a remote server:
    String connectionUrl = "jdbc:sqlserver://MyServer;databaseName=MyDatabase;integratedSecurity=true;encrypt=true;trustServerCertificate=true";
Note: For integrated security to work, you may need to ensure the correct authentication DLL (mssql-jdbc_auth-<version>.dll) is available in your Java application's library path, and you must use a compatible Microsoft JDBC Driver.

Using SQL Server Authentication (Username and Password)
This method uses a specific SQL Server login (username and password).
  • To a named instance (e.g., SQLEXPRESS):
    String connectionUrl = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=MyDatabase;user=myUsername;password=myPassword;encrypt=true;trustServerCertificate=true";
  • To a specific port (e.g., 1433):
    If you've configured SQL Server Express to listen on a fixed TCP port, you can use the port number directly, which is more efficient as it avoids a network round trip to resolve the instance name.
    String connectionUrl = "jdbc:sqlserver://MyServer:1433;databaseName=MyDatabase;user=myUsername;password=myPassword;encrypt=true;trustServerCertificate=true";

Important Considerations
  • Encryption: The Microsoft JDBC driver for SQL Server (since recent versions) requires a secure connection by default. It is recommended to include encrypt=true and, for development or self-signed certificates, trustServerCertificate=true.
  • Driver Download: Ensure you have the appropriate Microsoft JDBC Driver for SQL Server JAR file added to your project's classpath. The driver is available via Microsoft Learn or package managers like Maven.
  • TCP/IP: Make sure the SQL Server instance has the TCP/IP protocol enabled via the SQL Server Configuration Manager and that the firewall allows connections to the specified port.
source: https://www.google.com/search?q=ms+sql+server+express+2022+connection+string+jdbc
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Last edited:
Upvote 0
Top