ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 5454|ตอบกลับ: 6

[VB.NET] โค้ดการเชื่อมต่อฐานข้อมูล MySQL Server ด้วยการใช้งานคลาส และฟังค์ชั่น

[คัดลอกลิงก์]

308

กระทู้

498

โพสต์

5971

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
5971



สำหรับโค้ดชุดนี้แอดมินขอนำเสนอ การเชื่อมต่อฐานข้อมูล MySQL Server ด้วยการใช้งาน Class และ Function กันน่ะครับ ก็ขอให้ทุกๆท่านได้ศึกษาความเหมือน และความต่างกันเอาเองล่ะกัน แต่โดยปกติแอดมินจะถนัดในการใช้งานฟังค์ชั่นมากกว่าขอรับกระผม ... เนื่องจากว่าการล็อคอินจะต้องติดต่อกับ MySQL Server ให้ได้ก่อน หากติดต่อได้สำเร็จ ตัวแปรแบบ Public คือ blnConnect ก็จะถูกกำหนดให้เป็นจริง (True) ก่อนทำการล็อคอินเข้าสู่ระบบของ DataBase อีกรอบหนึ่งในตาราง tbluser ทำให้ไม่ต้องมาเสียเวลาในการ Connect เข้าสู่ Server อีกรอบ ในกรณีที่ผู้ใช้ใส่ชื่อหรือรหัสผ่านผิด ตารางข้อมูลตัวอย่างจะอยู่ในไฟล์โค้ดต้นฉบับเรียบร้อย ...

Add Reference ไฟล์ 2 ตัว ... Visual Basic Power Packs และ MySQL.Data ...


โค้ดหลักในหน้าจอล็อคอิน ...
  1. Imports MySql.Data.MySqlClient

  2. Public Class frmConnectMySQL

  3.     Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
  4.         If Trim(txtServer.Text.Length) = 0 Then
  5.             MessageBox.Show("Enter your DNS or IP Address.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  6.             txtServer.Focus()
  7.             Return
  8.         ElseIf Trim(txtDBName.Text.Length) = 0 Then
  9.             MessageBox.Show("Enter your DataBase Name.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  10.             txtDBName.Focus()
  11.             Return
  12.         ElseIf Trim(txtDBUserName.Text.Length) = 0 Then
  13.             MessageBox.Show("Enter your DataBase Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  14.             txtDBUserName.Focus()
  15.             Return
  16.         ElseIf Trim(txtDBPassword.Text.Length) = 0 Then
  17.             MessageBox.Show("Enter your DataBase Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  18.             txtDBPassword.Focus()
  19.             Return
  20.         End If

  21.         '// Connecto to MySQL Server.
  22.         '// Select only one to connect.
  23.         Call ConnectClass()
  24.         'Call ConnectFunction()
  25.     End Sub

  26.     '// Calling to Class in clsConnectMySQL.
  27.     Private Sub ConnectClass()
  28.         '// Create Instance Name from clsConnectMySQL.vb
  29.         Dim MyConnect As New clsConnectMySQL
  30.         If Not blnConnect Then
  31.             With MyConnect
  32.                 '// Assing the object property values
  33.                 .ServerName = txtServer.Text
  34.                 .DatabaseName = txtDBName.Text
  35.                 .UserID = txtDBUserName.Text
  36.                 .Password = txtDBPassword.Text
  37.                 '// Connection String
  38.                 Conn = .Connection
  39.                 '// Connect to MySQL Server Successfull.
  40.                 If Not IsNothing(Conn) Then
  41.                     blnConnect = True
  42.                     MessageBox.Show("Connection to MySQL Server successful.", "Login to Server", MessageBoxButtons.OK, MessageBoxIcon.Information)
  43.                 Else
  44.                     MessageBox.Show(.ErrorMsg, "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  45.                     Return
  46.                 End If
  47.             End With
  48.         End If
  49.         '// Login to User Table.
  50.         If blnConnect And LoginSystem() Then
  51.             MessageBox.Show("Operation Complete.")
  52.             'Me.Close()
  53.         End If
  54.     End Sub

  55.     '// Calling to Function in modDataBase.vb
  56.     Private Sub ConnectFunction()
  57.         '// blnConnect declare in modDataBase.vb and default valuse is FALSE.
  58.         If Not blnConnect Then
  59.             '// ConectMySQL in the modDataBase.vb
  60.             If ConnectMySQL(Trim(txtServer.Text), Trim(txtDBName.Text), txtDBUserName.Text.Trim, txtDBPassword.Text.Trim) Then
  61.                 MessageBox.Show("Connection to MySQL Server successful.", "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  62.             Else
  63.                 Me.Cursor = Cursors.Default
  64.                 Exit Sub
  65.             End If
  66.         End If
  67.         '// When successfully logged in to the server Next, check the logon table.
  68.         If blnConnect And LoginSystem() Then
  69.             MessageBox.Show("Operation Complete.")
  70.             'Me.Close()
  71.         End If
  72.     End Sub

  73.     ' / --------------------------------------------------------------------------------
  74.     ' / Login to User Table.
  75.     Private Function LoginSystem() As Boolean
  76.         LoginSystem = False
  77.         If Trim(txtUsername.Text.Length) = 0 Then
  78.             MessageBox.Show("Enter your Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  79.             txtUsername.Focus()
  80.             Exit Function
  81.         ElseIf Trim(txtPassword.Text.Length) = 0 Then
  82.             MessageBox.Show("Enter your Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  83.             txtPassword.Focus()
  84.             Exit Function
  85.         End If
  86.         '//
  87.         Try
  88.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  89.             Cmd = New MySqlCommand( _
  90.                 " SELECT * FROM tbluser WHERE " & _
  91.                 " Username = @UNAME AND Password = @PWD ", Conn)

  92.             Dim UsernameParam As New MySqlParameter("@UNAME", Me.txtUsername.Text)
  93.             Dim PasswordParam As New MySqlParameter("@PWD", Me.txtPassword.Text)

  94.             Cmd.Parameters.Add(UsernameParam)
  95.             Cmd.Parameters.Add(PasswordParam)

  96.             DR = Cmd.ExecuteReader()
  97.             '// Found data
  98.             If DR.HasRows Then
  99.                 MessageBox.Show("You can logged into system.", "LOGON SYSTEM", MessageBoxButtons.OK, MessageBoxIcon.Information)
  100.                 LoginSystem = True
  101.             Else
  102.                 LoginSystem = False
  103.                 MessageBox.Show("Enter your Username, Password is incorrect.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  104.                 txtUsername.Focus()
  105.             End If
  106.             DR.Close()
  107.             Cmd.Dispose()
  108.             '//
  109.             strSQL = _
  110.                 " SELECT * FROM tbluser " & _
  111.                 " WHERE Username = " & "'" & txtUsername.Text & "'"
  112.             DA = New MySqlDataAdapter(strSQL, Conn)
  113.             DS = New DataSet
  114.             DA.Fill(DS)
  115.             With DS.Tables(0)
  116.                 '// modStructure.vb
  117.                 CurrUser.USER_USERPK = Val(.Rows(0)("UserPK").ToString)
  118.                 CurrUser.USER_USERNAME = .Rows(0)("Username").ToString()
  119.                 CurrUser.USER_COMPLETENAME = .Rows(0)("CompleteName").ToString()
  120.                 CurrUser.USER_TIMELOGIN = Now() ' Time Stamp
  121.                 ' True = Admin
  122.                 CurrUser.USER_ISADMIN = CBool(.Rows(0)("IsAdmin").ToString)
  123.             End With
  124.             DS.Dispose()
  125.             DA.Dispose()
  126.             Conn.Dispose()
  127.             Conn.Close()
  128.         Catch ex As Exception
  129.             'MessageBox.Show(ex.Message)
  130.         End Try
  131.         '//
  132.     End Function

  133.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  134.         Me.Close()
  135.     End Sub

  136.     Private Sub frmConnectMySQL_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  137.         If Not IsNothing(Conn) Then
  138.             If Conn.State = ConnectionState.Open Then Conn.Close()
  139.             Conn.Dispose()
  140.             Conn = Nothing
  141.         End If
  142.         Me.Dispose()
  143.         GC.SuppressFinalize(Me)
  144.         Application.Exit()
  145.     End Sub

  146.     Private Sub frmConnectMySQL_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  147.         Me.CenterToScreen()
  148.     End Sub

  149. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในคลาส clsConnectMySQL.vb ...
  1. Imports MySql.Data.MySqlClient

  2. Public Class clsConnectMySQL
  3.     Private _Connection As New MySqlConnection
  4.     Private _ErrorMsg As String
  5.     Private _ServerName As String
  6.     Private _DatabaseName As String
  7.     Private _UserID As String
  8.     Private _Password As String

  9.     Public WriteOnly Property ServerName() As String
  10.         Set(ByVal value As String)
  11.             _ServerName = value
  12.         End Set
  13.     End Property

  14.     Public WriteOnly Property DatabaseName() As String
  15.         Set(ByVal value As String)
  16.             _DatabaseName = value
  17.         End Set
  18.     End Property

  19.     Public WriteOnly Property UserID() As String
  20.         Set(ByVal value As String)
  21.             _UserID = value
  22.         End Set
  23.     End Property

  24.     Public WriteOnly Property Password() As String
  25.         Set(ByVal value As String)
  26.             _Password = value
  27.         End Set
  28.     End Property

  29.     Public ReadOnly Property ErrorMsg() As String
  30.         Get
  31.             Return _ErrorMsg
  32.         End Get
  33.     End Property

  34.     Public Function Connection() As MySqlConnection
  35.         Connection = Nothing
  36.         Try
  37.             _Connection.ConnectionString = _
  38.                 " Server = " & _ServerName & ";" & _
  39.                 " Database = " & _DatabaseName & ";" & _
  40.                 " User ID = " & _UserID & ";" & _
  41.                 " Password = " & _Password & ";" & _
  42.                 " Port = 3306;" & _
  43.                 " CharSet = utf8; " & _
  44.                 " Connect Timeout = 90; " & _
  45.                 " Pooling = True; " & _
  46.                 " Persist Security Info = False; " & _
  47.                 " Connection Reset = False; " & _
  48.                 " Default Command Timeout = 90; " & _
  49.                 " Connection Lifetime = 0;"
  50.             _Connection.Open()
  51.             If _Connection.State = ConnectionState.Open Then _Connection.Close()
  52.             _Connection.Dispose()
  53.             Return _Connection
  54.         Catch ex As Exception
  55.             _ErrorMsg = ex.Message
  56.         End Try
  57.     End Function

  58. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดฟังค์ชั่นในโมดูล modDataBase.vb ...
  1. Imports MySql.Data.MySqlClient

  2. Module modDataBase
  3.     '// Declare variable one time but use many times.
  4.     Public Conn As MySqlConnection
  5.     Public Cmd As MySqlCommand
  6.     Public DR As MySqlDataReader
  7.     Public DA As MySqlDataAdapter
  8.     Public DS As DataSet
  9.     Public DT As DataTable
  10.     Public strSQL As String '// Major SQL
  11.     Public strStmt As String    '// Minor SQL
  12.     '//
  13.     Public blnConnect As Boolean = False

  14.     ' / --------------------------------------------------------------------------------
  15.     '// MySQL Server Connection Test with VB.NET (2010).
  16.     Public Function ConnectMySQL(ByVal SERVER As String, ByVal DB As String, ByVal UID As String, PWD As String) As Boolean
  17.         '// Server=localhost; DataBase=DB; User ID=YourUserID; Password=YourPassword;
  18.         Dim strCon As String = _
  19.             " Server = " & SERVER & "; " & _
  20.             " Database = " & DB & "; " & _
  21.             " User ID = " & UID & "; " & _
  22.             " Password = " & PWD & "; " & _
  23.             " Port = 3306; " & _
  24.             " CharSet = utf8; " & _
  25.             " Connect Timeout = 90; " & _
  26.             " Pooling = True; " & _
  27.             " Persist Security Info = True; " & _
  28.             " Connection Reset = False; " & _
  29.             " Default Command Timeout = 90; "

  30.         Conn = New MySqlConnection
  31.         Conn.ConnectionString = strCon
  32.         Try
  33.             Conn.Open()
  34.             ConnectMySQL = True
  35.             blnConnect = True
  36.         Catch ex As Exception
  37.             MessageBox.Show(ex.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  38.             ConnectMySQL = False
  39.             blnConnect = False
  40.         Finally
  41.             Conn.Dispose()
  42.             Conn.Close()
  43.         End Try
  44.     End Function

  45. End Module
คัดลอกไปที่คลิปบอร์ด

โค้ดโครงสร้าง (Structure) ในโมดูล modStructure.vb ... เก็บข้อมูลแบบโครงสร้างของ Users ...
  1. Module modStructure
  2.     ' / ------------------------------------------------------------------
  3.     ' User-defined Types (UDTs)
  4.     Public Structure USER_INFO
  5.         ' Primary Key of User
  6.         Dim USER_USERPK As Integer
  7.         ' Username or UserID
  8.         Dim USER_USERNAME As String
  9.         ' Password
  10.         Dim USER_PASSWORD As String
  11.         ' Administrator is True
  12.         Dim USER_ISADMIN As Boolean
  13.         ' Completename
  14.         Dim USER_COMPLETENAME As String
  15.         ' Time Stamp
  16.         Dim USER_TIMELOGIN As Date
  17.     End Structure

  18.     ' User-defined Types (UDTs)
  19.     Public Structure DB_INFO
  20.         ' SERVER
  21.         Dim SERVER As String
  22.         Dim DB As String
  23.         Dim UID As String
  24.         Dim PWD As String
  25.     End Structure

  26.     ' USER_INFO is a template, It can not be stored data.
  27.     ' Assign a variable to a Data Structure (UDTs)
  28.     ' Run through the series via CurrUser.
  29.     Public CurrUser As USER_INFO
  30.     ' Example:
  31.     ' CurrUser.USER_NAME ... Keep UserName string
  32.     ' CurrUser.USER_ISADMIN ... Keep status true/false
  33.     ' / ------------------------------------------------------------------
  34.     Public MyDB As DB_INFO

  35. End Module
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

0

กระทู้

33

โพสต์

372

เครดิต

Full Member

Rank: 3Rank: 3

เครดิต
372
โพสต์ 2020-7-14 15:48:25 | ดูโพสต์ทั้งหมด

ขอบคุณคับ

4

กระทู้

15

โพสต์

249

เครดิต

Full Member

Rank: 3Rank: 3

เครดิต
249
โพสต์ 2020-7-15 16:47:08 จากอุปกรณ์พกพา | ดูโพสต์ทั้งหมด

น้อมรับไปทดสอบ

4

กระทู้

15

โพสต์

249

เครดิต

Full Member

Rank: 3Rank: 3

เครดิต
249
โพสต์ 2020-7-15 16:47:44 จากอุปกรณ์พกพา | ดูโพสต์ทั้งหมด

ขอบคุณครับ ^_^

0

กระทู้

1

โพสต์

56

เครดิต

Member

Rank: 2

เครดิต
56
โพสต์ 2020-8-19 23:51:43 | ดูโพสต์ทั้งหมด

ขอบคุณครับ แต่ทำไมของผม Run ไม่ผ่าน มันขึ้นข้อความนี้ครับ Error        1        Couldn't process file frmConnectMySQL.resx due to its being in the Internet or Restricted zone or having the mark of the web on the file. Remove the mark of the web if you want to process these files.        ConnectionMySQL

5

กระทู้

21

โพสต์

165

เครดิต

Member

Rank: 2

เครดิต
165
โพสต์ 2020-9-28 19:52:21 | ดูโพสต์ทั้งหมด

ขอบคุณครับ อาจารย์

0

กระทู้

1

โพสต์

10

เครดิต

Newbie

Rank: 1

เครดิต
10
โพสต์ 2023-5-11 23:39:09 | ดูโพสต์ทั้งหมด

ขอบพระคุณครับ
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-3-28 20:09 , Processed in 0.247709 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้