thongkorn โพสต์ 2020-6-20 20:16:35

[B4A] การเชื่อมต่อฐานข้อมูล MySQL ทั้งแบบ Local/Remote ผ่านทางการใช้งาน JDBC

http://www.g2gnet.com/webboard/images/b4a/mysqljdbc.png


สำหรับบทความชุดนี้เป็นการเชื่อมต่อฐานข้อมูล MySQL ทั้งแบบ Local/Remote ผ่านทาง JDBC เป็นการติดต่อโดยตรงเข้าสู่ฐานข้อมูลครับผม ...

ดาวน์โหลด B4A เพื่อติดตั้งใช้งานฟรี ...

ดาวน์โหลดโค้ดต้นฉบับสำหรับบทความชุดนี้ ...

ไฟล์ Libraries จะอยู่ใน Zip File เมื่อแตกออกมาให้คัดลอกไฟล์ทั้งหมดไปเก็บไว้ที่ C:\Program Files (x86)\Anywhere Software\Basic4android\Libraries ...
http://www.g2gnet.com/webboard/images/b4a/mysqljdbclibfile.png

ไฟล์ Libraries ที่จำเป็นต้องใช้งาน ...
http://www.g2gnet.com/webboard/images/b4a/mysqljdbclib.png

ใน phpMyAdmin สำหรับการ Import ไฟล์ SQL ตัวอย่างเข้ามา ...
http://www.g2gnet.com/webboard/images/b4a/mysqljdbcimport.png


ตารางข้อมูลตัวอย่าง ...
http://www.g2gnet.com/webboard/images/b4a/mysqljdbcdata.png

มาดูโค้ดกันเถอะ ... Starter.bas
#RegionService Attributes
        #StartAtBoot: False
        #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
        'These global variables will be declared once when the application starts.
        'These variables can be accessed from all modules.
        '// Remote MySQL Server
        Public mysql As JdbcSQL
        Public driver As String = "com.mysql.jdbc.Driver"
        '// Link to Remote MySQL/Table Name
        Public jdbcUrl As String = "jdbc:mysql://www.remotemysql.com/PgseQEAkdl?useSSL=false"
        Public Username As String = "USERNAME"
        Public Password As String = "PASSWORD"
        '// Localhost
        'Private jdbcUrl As String = "jdbc:mysql://192.168.1.11:3306/contact"
        'Private Username As String = "USERNAME"
        'Private Password As String = "PASSWORD"
End Sub

Sub Connect As ResumableSub
        mysql.InitializeAsync("mysql", driver, jdbcUrl, Username, Password)
        Wait For MySQL_Ready (Success As Boolean)
        If Success = False Then
                Log("Check unfiltered logs for JDBC errors.")
        End If
        Return Success
End Sub

Sub CloseConnection
        mysql.Close
End Sub

Sub DisableStrictMode
        Dim jo As JavaObject
        jo.InitializeStatic("android.os.Build.VERSION")
        If jo.GetField("SDK_INT") > 9 Then
                Dim policy As JavaObject
                policy = policy.InitializeNewInstance("android.os.StrictMode.ThreadPolicy.Builder", Null)
                policy = policy.RunMethodJO("permitAll", Null).RunMethodJO("build", Null)
                Dim sm As JavaObject
                sm.InitializeStatic("android.os.StrictMode").RunMethod("setThreadPolicy", Array(policy))
        End If
End Sub

Sub Service_Create
        'This is the program entry point.
        'This is a good place to load resources that are not specific to a single activity.
        'need to disable it as reading from large JdbcResultSet will cause network requests to be sent on the main thread.
        DisableStrictMode
End Sub

Sub Service_Start (StartingIntent As Intent)
        Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
End Sub

Sub Service_TaskRemoved
        'This event will be raised when the user removes the app from the recent apps list.
End Sub

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

Sub Service_Destroy

End Sub

โค้ดในส่วนของ Main ...
#RegionProject Attributes
        #ApplicationLabel: Connect Remote MySQL
        #VersionCode: 1
        #VersionName:
        'SupportedOrientations possible values: unspecified, landscape or portrait.
        #SupportedOrientations: unspecified
        #CanInstallToExternalStorage: False
#End Region

#RegionActivity Attributes
        #FullScreen: False
        #IncludeTitle: True
    'MySQL Connector/J Driver
    #AdditionalJar: mysql-connector-java-5.1.47-bin.jar
        '#AdditionalJar: mysql-connector-java-5.1.34-bin
        '#AdditionalJar: mysql-connector-java-5.1.49-bin.jar
        #BridgeLogger: true
#End Region

'// https://www.b4x.com/android/help/jdbcsql.html
Sub Process_Globals
        'These global variables will be declared once when the application starts.
        'These variables can be accessed from all modules.
End Sub

Sub Globals
        'These global variables will be redeclared each time the activity is created.
        'These variables can only be accessed from this module.
        Private Kanit As CustomFonts
        Private ListView1 As ListView
        Private ProgressBar1 As ProgressBar
End Sub


Sub Activity_Create(FirstTime As Boolean)
        Activity.LoadLayout("main")
        Activity.Title="Connect Remote MySQL "
        '// Set Own Font.
        Kanit.Initialize("Kanit-Regular.ttf")
        Kanit.SetCustomFontsToAllViews(Activity)
        '// Initialized.
        ProgressBar1.Visible = True
        Wait For (Starter.Connect) Complete (Success As Boolean)
        'Log(Success)
        If Success Then
                Dim jsql As JdbcResultSet
                Starter.mysql.Initialize2(Starter.driver, Starter.jdbcUrl, Starter.Username, Starter.Password)
                '/ Localhost Query
                '/jsql=Starter.mysql.ExecQuery("SELECT ContactPK, ContactID, FullName FROM contact.tblcontact ")
                jsql = Starter.mysql.ExecQuery("SELECT ContactPK, ContactID, FullName FROM tblcontact ORDER BY ContactID")
                Do While jsql.NextRow
                        'Log(jsql.GetString("ContactID"))
                        ListView1.AddTwoLines2(jsql.GetString("ContactID"), jsql.GetString("Fullname"), jsql.GetString("ContactPK"))
                Loop
                Starter.CloseConnection
        End If
        ProgressBar1.Visible = False
End Sub
       
Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

หน้า: [1]
ดูในรูปแบบกติ: [B4A] การเชื่อมต่อฐานข้อมูล MySQL ทั้งแบบ Local/Remote ผ่านทางการใช้งาน JDBC