Android Question Connect to SQL Server

catyinwong

Active Member
Licensed User
Longtime User
Sorry I am so confused and have no idea how to put things up. I am using azure database and the connection strings are as the following:

ADO.NET
Server=tcp:testingserverabc.database.windows.net,1433;Initial Catalog=testing;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;


JDBC
jdbc:sqlserver://testingserverabc.database.windows.net:1433;database=testing;user=testingadmin@testingserverabc;password={your_password_here};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;


ODBC
Driver={ODBC Driver 13 for SQL Server};Server=tcp:testingserverabc.database.windows.net,1433;Database=testing;Uid=testingadmin@testingserverabc;Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;

Anyone can help translate to the B4A JdbcSQL setting for me ? :(

Public mysql As JdbcSQL
Private driver As String = ???
Private jdbcUrl As String = ???
Private Username As String = ???
Private Password As String = ???
 

catyinwong

Active Member
Licensed User
Longtime User
Yes... and I don't understand that at all... i downloaded the example and work with some time, still don't have a clue...

And I am wondering if it is a very complicated question, coz there isn't anyone who want to give me the answer even if I post all my SQL address, server and password here... :'(
 
Upvote 0

catyinwong

Active Member
Licensed User
Longtime User
This question originated from the B4A tutorial example: https://www.b4x.com/android/forum/threads/jdbcsql-directly-connect-to-remote-databases.84016/

But it doesn't work for the MSSQL in azure (coz i don't know what drive and jdbcUrl means), I have posted everything about my azure database. Anyone helps me to give me an answer how it applies to the example???? This is the forth post I have been asking, pretty desperate.... Anyone telling me the answer instead of giving me links or examples??? I CAN'T FIGURE IT OUT AFTER READING THEM AND THAT'S WHY I AM ASKING IN THE FIRST PLACE :(:(:(:(:(:(:(:(:(:(:(:(:(:(

Public mysql As JdbcSQL
Private driver As String = ???
Private jdbcUrl As String = ???
Private Username As String = ???
Private Password As String = ???



ADO.NET
Server=tcp:testingserverabc.database.windows.net,1433;Initial Catalog=testing;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;


JDBC
jdbc:sqlserver://testingserverabc.database.windows.net:1433;database=testing;user=testingadmin@testingserverabc;password={your_password_here};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;


ODBC
Driver={ODBC Driver 13 for SQL Server};Server=tcp:testingserverabc.database.windows.net,1433;Database=testing;Uid=testingadmin@testingserverabc;Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;
 
Upvote 0

kisoft

Well-Known Member
Licensed User
Longtime User
Hi
You must wait for Erel. More faith and patience.
Most on the forum probably use MySQL and jRDC2. This solution is better and safer.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. You must read and understand this tutorial: https://www.b4x.com/android/forum/threads/jdbcsql-directly-connect-to-remote-databases.84016/
2. You need to download the relevant JDBC jar file and add a reference with #AdditionalJar.
3. You should never make duplicate posts: https://www.b4x.com/android/forum/threads/how-to-connect-to-mssql-with-jdbcsql.95389/#post-602711
4. See this post: https://www.b4x.com/android/forum/threads/mssql-server-with-b4j.77711/#post-492287
Unlike my answer in the other thread you made it is based on Microsoft JDBC driver.
 
Upvote 0

npsonic

Active Member
Licensed User
It's not good idea to connect app directly to sql.

You may want to check this article. It describes how you can use Azure Mobile Service to connect Azure Cloud SQL.
Just create new cloud-based bankend service and follow instructions. Download SDK and add the JAR file with "#AdditionalJar: <your .jar>"
You can use Inline Java or B4A JavaObject to use library. What ever is easier for you.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Here is an example with the four variables set: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-573074.
Please note that the poster still had issues and this was my reply: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-573443
The usage of the other driver was confirmed in the same thread: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-591195

Since this has been awhile ago (5 months), the MS driver may work with newer version of Android. But that is for you to test since 1) you would like to connect to MS SQL directly and 2) you seem to have the means to test it since you seem to have an MS SQL server up and running.
 
Upvote 0

catyinwong

Active Member
Licensed User
Longtime User
Here is an example with the four variables set: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-573074.
Please note that the poster still had issues and this was my reply: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-573443
The usage of the other driver was confirmed in the same thread: https://www.b4x.com/android/forum/threads/mssql-jdbc-minimalistic-example.90548/#post-591195

Since this has been awhile ago (5 months), the MS driver may work with newer version of Android. But that is for you to test since 1) you would like to connect to MS SQL directly and 2) you seem to have the means to test it since you seem to have an MS SQL server up and running.

Thank you so much OliverA!!! I have downloaded the example and tested. It returns a success in connecting to the server but an error of ExecQueryAsync (invalid object name) T^T

Log:

*** Debugger waiting for connection (1) ***
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
Class anywheresoftware.b4a.B4AThreadPool failed lock verification and will run slower.
** Activity (main) Resume **
Class net.sourceforge.jtds.jdbc.JtdsConnection failed lock verification and will run slower.
Class net.sourceforge.jtds.jdbc.Semaphore failed lock verification and will run slower.
Class net.sourceforge.jtds.jdbc.SharedSocket failed lock verification and will run slower.
Class net.sourceforge.jtds.util.TimerThread failed lock verification and will run slower.
Class net.sourceforge.jtds.jdbc.TdsCore failed lock verification and will run slower.
Class net.sourceforge.jtds.jdbc.JtdsStatement failed lock verification and will run slower.
Class net.sourceforge.jtds.jdbc.JtdsResultSet failed lock verification and will run slower.
Connect Success
ThreadedRenderer.create() translucent=true
Input channel constructed: fd=79
setView = DecorView@3ae93f1[main] touchMode=true
dispatchAttachedToWindow
Class net.sourceforge.jtds.jdbc.JtdsPreparedStatement failed lock verification and will run slower.
Relayout returned: oldFrame=[0,0][0,0] newFrame=[28,839][1052,1143] result=0x27 surface={isValid=true 548136594944} surfaceGenerationChanged=true
mHardwareRenderer.initialize() mSurface={isValid=true 548136594944} hwInitialized=true
MSG_WINDOW_FOCUS_CHANGED 1
mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548136594944}
MSG_RESIZED_REPORT: frame=Rect(28, 839 - 1052, 1143) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
MSG_WINDOW_FOCUS_CHANGED 0
java.sql.SQLException: Invalid object name 'Switches'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:1029)
at anywheresoftware.b4j.objects.SQL.ExecQuery2(SQL.java:343)
at anywheresoftware.b4j.objects.SQL$3.run(SQL.java:297)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
mHardwareRenderer.destroy()#4
dispatchDetachedFromWindow
Input channel destroyed: fd=79
ThreadedRenderer.create() translucent=true
Input channel constructed: fd=79
setView = DecorView@1e8bd36[main] touchMode=true
dispatchAttachedToWindow
Relayout returned: oldFrame=[0,0][0,0] newFrame=[28,704][1052,1279] result=0x27 surface={isValid=true 548136594944} surfaceGenerationChanged=true
mHardwareRenderer.initialize() mSurface={isValid=true 548136594944} hwInitialized=true
onsize change changed
onsize change changed
MSG_WINDOW_FOCUS_CHANGED 1
mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548136591360}
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548136594944}
MSG_RESIZED_REPORT: frame=Rect(28, 704 - 1052, 1279) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
MSG_WINDOW_FOCUS_CHANGED 0
mHardwareRenderer.destroy()#4
dispatchDetachedFromWindow
System.exit called, status: 0
VM exiting with result code 0, cleanup skipped.
SS_ART_lib : permission is absent: /data/app/b4a.example-1/base.apk
SS_ART_lib : access to SS denied
SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=b4a.example
Class anywheresoftware.b4a.BA failed lock verification and will run slower.
Common causes for lock verification issues are non-optimized dex code
and incorrect proguard optimizations.
Starting remote logger. Port: 35352
init sf_choreo_doframe debug_Level : 0x4f4cdebug_game_running : false
ThreadedRenderer.create() translucent=false
Input channel constructed: fd=59
setView = DecorView@2ea57a8[main] touchMode=true
dispatchAttachedToWindow
Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1080,1920] result=0x27 surface={isValid=true 548136628224} surfaceGenerationChanged=true
mHardwareRenderer.initialize() mSurface={isValid=true 548136628224} hwInitialized=true
QUALCOMM build : cce9f40, Ifcb662fdfd
Build Date : 07/11/17
OpenGL ES Shader Compiler Version: XE031.09.00.04
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
*** Debugger waiting for connection (0) ***
Initialized EGL, version 1.4
Swap behavior 1
MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1080, 1920) ci=Rect(0, 63 - 0, 0) vi=Rect(0, 63 - 0, 0) or=1
MSG_WINDOW_FOCUS_CHANGED 1
mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548136628224}
Starting input: tba=android.view.inputmethod.EditorInfo@d0b9fd nm : b4a.example ic=null
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Code please (including setting up SQL object. Please use code tags).
 
Upvote 0

catyinwong

Active Member
Licensed User
Longtime User
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
    
    #AdditionalJar: jtds-1.3.1.jar

#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Globals
    
End Sub
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

    Dim sql1 As JdbcSQL', Str As StringUtils
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Connect("Connect_Ready")
End Sub
'I use Callback to tell me what sub to return to if the connection fails and I have to re-establish it.
Public Sub Connect(CallBack As String)

sql1.Close
'sql1.InitializeAsync("Connect", "net.sourceforge.jtds.jdbc.Driver", "jdbc:jtds:sqlserver://192.168.1.5:65218;databaseName=MyDBName;user=UserName;password=MyPW;appname=SKMJL;wsid=MyWS;loginTimeout=10", "UserName", "MyPW")  'sql 2012

    sql1.InitializeAsync("Connect", "net.sourceforge.jtds.jdbc.Driver", "jdbc:jtds:sqlserver://XXXXX.database.windows.net:1433;database=XXXXX;user=XXXXX@xxxxx;password=XXXXX;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;", "XXXX", "XXXXX")  'sql 2012

'Catch
'Msgbox2Async("Connection to the network failed: " & CRLF & LastException.Message , "Network Error", "OK","","", Null, True)
'End Try

End Sub

'I have left an example SQL Select statement in here, ExecQueryAsync
Sub Connect_Ready (Success As Boolean)
    ProgressDialogHide
    If Success = False Then
        MsgboxAsync("Failed connect to the server. Server is not available, database is not availble, connect string is wrong, or you are having network/firewall issues. Contact your system administrator.", "Network/SQL Error")
        MsgboxAsync(LastException.Message,"JAva Error:")
        Return
    End If
    Log("Connect Success")
    Try
        'Connecting = False
        ProgressDialogShow("Getting Configuration Data")
        'GetCount 'Check user counts
        Dim SenderFilter As Object = sql1.ExecQueryAsync("Switches", "SELECT * FROM FTP", Null)
        'sql1.s
        Wait For (SenderFilter) Switches_QueryComplete (Success2 As Boolean, Crsr As JdbcResultSet)
        If Success2 = False Then
            ProgressDialogHide
            MsgboxAsync("Failed to get the required Configuration (Switches) data - Cannot continue." & CRLF & LastException.Message, "DB Error")
            'Screen = "Home"
            Return
        End If
    Catch
        Log(LastException.Message)
        ToastMessageShow("Connect_Ready" & CRLF & LastException.Message, True)
    End Try
 
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You should add Log messages instead of MsgboxAsync.

I don't understand this error:

java.sql.SQLException: Invalid object name 'Switches'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)

What happens if you change the code to:
B4X:
Dim SenderFilter As Object = sql1.ExecQueryAsync("sql", "SELECT * FROM FTP", Null)
        'sql1.s
        Wait For (SenderFilter) SQL_QueryComplete (Success2 As Boolean, Crsr As JdbcResultSet)

Do you get the exact same error message?
 
Upvote 0

AndresArballo

New Member
Lo siento, estoy tan confundido y no tengo idea de cómo poner las cosas. Estoy usando una base de datos azul y las cadenas de conexión son las siguientes:

ADO.NET
Server=tcp:testingserverabc.database.windows.net,1433;Initial Catalog=testing;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False; Tiempo de espera de conexión = 30;


JDBC
jdbc:sqlserver://testingserverabc.database.windows.net:1433;database=testing;user=testingadmin@testingserverabc;password={su_contraseña_aquí};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net; inicio de sesiónTiempo de espera=30;


ODBC
Driver={Controlador ODBC 13 para SQL Server};Server=tcp:testingserverabc.database.windows.net,1433;Database=testing;Uid=testingadmin@testingserverabc;Pwd={su_contraseña_aquí};Encrypt=sí;TrustServerCertificate=no;Connection Tiempo de espera=30;

¿Alguien puede ayudarme a traducir a la configuración B4A JdbcSQL?:(

MySQL público como JdbcSQL
Conductor privado As String = ???
jdbcUrl privado como cadena = ???
Nombre de usuario privado como cadena = ???
Contraseña privada como cadena = ???
Hola tengo el mismo problema. lo resolviste?
 
Upvote 0
Top