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

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

[VB.NET] การเชื่อมต่อ MySQL Server ทั้งแบบ Local และ Remote DataBase

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

322

กระทู้

515

โพสต์

6853

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6853



โค้ด VB.NET (2010) ชุดนี้เพื่อทดสอบการเชื่อมต่อ MySQL Server (เวอร์ชั่น 5.7.17) แบบ Local DataBase (ระบบ LAN) และแบบ Remote DataBase เพื่อทำให้สามารถเชื่อมต่อจากเครื่องลูก (Client) ของ Windows Application ผ่านอินเทอร์เน็ตเข้ามายังตัว Server ได้ รวมไปถึงการตั้งค่าที่จำเป็นต่างๆ แอดมินได้ย้ายให้ไปเก็บลง Registry ของ Windows แทน ... จากเวอร์ชั่นก่อนๆที่ผ่านมาในส่วนของ Local DataBase ไม่มีปัญหาใดๆ แต่มักจะมีปัญหากับการใช้งานแบบ Remote DataBase ซึ่งครั้งนี้แอดมินได้แก้ไขปรับแต่งโค้ดให้มีการเชื่อมต่อและทำงานได้ (เกือบ) 100% ... ผิดถูกประการใดช่วยแจ้งให้แอดมินได้ทราบด้วย จักเป็นพระคุณอย่างยิ่ง

มาดูโค้ดกันเถอะ ... เราจะเริ่มต้นที่ frmLogin เป็นฟอร์ม Start Up ...
  1. Imports MySql.Data.MySqlClient
  2. Imports Microsoft.Win32
  3. Imports System.IO

  4. Public Class frmLogin

  5.     '// ----------------------------------------------------------------------------------------------------
  6.     '// S T A R T . . . H E R E
  7.     '// ----------------------------------------------------------------------------------------------------
  8.     Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  9.         '//
  10.     End Sub

  11.     '// ----------------------------------------------------------------------------------------------------
  12.     '// ล็อคอินเข้าสู่ระบบ
  13.     '// ----------------------------------------------------------------------------------------------------
  14.     Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
  15.         '// การตรวจสอบค่าว่างสำหรับ TextBox ด้วยการใช้ Dictionary ในการจับคู่
  16.         '// Key: TextBox, Value: ข้อความแจ้งเตือน
  17.         '// สร้าง Dictionary สำหรับ TextBox และข้อความแจ้งเตือน
  18.         Dim RequiredFields As New Dictionary(Of TextBox, String) From {
  19.             {txtUsername, "Enter your Username."},
  20.             {txtPassword, "Enter your Password."}
  21.         }
  22.         '// ตรวจสอบแต่ละฟิลด์ใน Dictionary
  23.         For Each Field In RequiredFields
  24.             If String.IsNullOrWhiteSpace(Field.Key.Text) Then
  25.                 MessageBox.Show(Field.Value, "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  26.                 Field.Key.Focus()
  27.                 Return
  28.             End If
  29.         Next
  30.         '// อ่านค่า Connection String จาก Registry (หากกรณีที่มีการเปลี่ยนแปลงค่าใน frmConnection.vb)
  31.         MySQLConnectionManager.LoadFromRegistry()
  32.         '// ตรวจสอบการ Connection ก่อนที่จะเข้าไปอ่านฐานข้อมูลใน Payroll
  33.         If Not MySQLConnectionManager.TestConnection() Then
  34.             MessageBox.Show("Connection Manager is not initialized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  35.             '// เปิดฟอร์มการตั้งค่า Connection
  36.             frmConnection.ShowDialog()
  37.             Return
  38.         End If
  39.         '// ตรวจสอบการ Connection ก่อนที่จะเข้าไปอ่านฐานข้อมูลใน Payroll
  40.         Using Conn As New MySqlConnection(MySQLConnectionManager.GetConnectionString())
  41.             Try
  42.                 Conn.Open()
  43.                 '// ตรวจสอบข้อมูลผู้ใช้ในฐานข้อมูล
  44.                 If ValidateUser(Conn, txtUsername.Text, txtPassword.Text) Then
  45.                     MessageBox.Show("เข้าสู่ระบบสำเร็จสมบูรณ์", "สำเร็จ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  46.                     Me.Hide()
  47.                     Dim MainForm As New frmMain
  48.                     MainForm.ShowDialog()
  49.                     '// เมื่อฟอร์มหลักปิด ก็กลับมาปิดฟอร์มตัวมันเองด้วย
  50.                     Me.Close()
  51.                 Else
  52.                     MessageBox.Show("Username หรือ Password ไม่ถูกต้อง", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
  53.                 End If
  54.             Catch ex As Exception
  55.                 MessageBox.Show("เกิดข้อผิดพลาด: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  56.                 frmConnection.ShowDialog()
  57.             End Try
  58.         End Using
  59.     End Sub

  60.     '// ----------------------------------------------------------------------------------------------------
  61.     '// ตรวจสอบ Username และ Password ในตารางข้อมูล tblUser
  62.     '// ----------------------------------------------------------------------------------------------------
  63.     Private Function ValidateUser(ByVal Conn As MySqlConnection, ByVal username As String, ByVal password As String) As Boolean
  64.         Dim query As String = "SELECT * FROM tblUser WHERE username = @username AND password = @password"
  65.         Using cmd As New MySqlCommand(query, Conn)
  66.             cmd.Parameters.AddWithValue("@username", username)
  67.             cmd.Parameters.AddWithValue("@password", password)
  68.             Using reader As MySqlDataReader = cmd.ExecuteReader()
  69.                 If reader.HasRows Then
  70.                     While reader.Read()
  71.                         '// เก็บข้อมูลการเข้าใช้งานของผู้ใช้ โดยประกาศเป็น Global Variable สำหรับข้อมูลของผู้ใช้งาน
  72.                         '// Public CurrUser As New MySQLUserInfo (อยู่ใน modGlobalVariables.vb)
  73.                         CurrUser.UserPK = CInt(reader("UserPK").ToString())
  74.                         CurrUser.Username = reader("Username").ToString()
  75.                         CurrUser.CompleteName = reader("CompleteName").ToString()
  76.                         CurrUser.TimeLogin = DateTime.Now() '// Time Stamp
  77.                         CurrUser.IsAdmin = CBool(reader("IsAdmin").ToString())
  78.                     End While
  79.                     Return True
  80.                 Else
  81.                     Return False
  82.                 End If
  83.             End Using
  84.         End Using
  85.     End Function

  86.     '// ----------------------------------------------------------------------------------------------------
  87.     '// ตั้งค่า Connection
  88.     '// ----------------------------------------------------------------------------------------------------
  89.     Private Sub btnConnection_Click(sender As System.Object, e As System.EventArgs) Handles btnConnection.Click
  90.         frmConnection.ShowDialog()
  91.     End Sub

  92.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  93.         Me.Close()
  94.     End Sub

  95.     Private Sub frmLogin_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  96.         Me.Dispose()
  97.         GC.SuppressFinalize(Me)
  98.     End Sub

  99.     Private Sub txtUsername_GotFocus(sender As Object, e As System.EventArgs) Handles txtUsername.GotFocus
  100.         Call EnglishLanguage()
  101.     End Sub

  102.     Private Sub txtUsername_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtUsername.KeyPress
  103.         If Asc(e.KeyChar) = 13 Then
  104.             e.Handled = True
  105.             SendKeys.Send("{TAB}")
  106.         End If
  107.     End Sub

  108.     Private Sub txtPassword_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtPassword.KeyPress
  109.         If Asc(e.KeyChar) = 13 Then
  110.             e.Handled = True
  111.             Call btnLogin_Click(sender, e)
  112.         End If
  113.     End Sub

  114.     Private Sub txtPassword_GotFocus(sender As Object, e As System.EventArgs) Handles txtPassword.GotFocus
  115.         Call EnglishLanguage()
  116.     End Sub

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

โค้ดในส่วนของการทำการเชื่อมต่อ MySQL Server ... frmConnection.vb ...
  1. Imports MySql.Data.MySqlClient
  2. Imports Microsoft.Win32

  3. Public Class frmConnection
  4.     Private ConnectionManager As New MySQLConnectionManager()

  5.     '// ----------------------------------------------------------------------------------------------------
  6.     '// S T A R T ... H E R E
  7.     '// ----------------------------------------------------------------------------------------------------
  8.     Private Sub frmConnection_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  9.         '// อ่านค่า Connection String จาก Registry
  10.         MySQLConnectionManager.LoadFromRegistry()
  11.         '// โหลดค่าจาก ConnectionManager
  12.         Call LoadSettings()
  13.     End Sub

  14.     Private Sub LoadSettings()
  15.         '// ตรวจสอบว่า ConnectionManager มีค่าหรือไม่
  16.         If ConnectionManager IsNot Nothing Then
  17.             txtHost.Text = MySQLConnectionManager.Host
  18.             txtDBName.Text = MySQLConnectionManager.DBName
  19.             txtDBPort.Text = MySQLConnectionManager.DBPort
  20.             txtDBUsername.Text = MySQLConnectionManager.DBUsername
  21.             txtDBPassword.Text = MySQLConnectionManager.DBPassword
  22.         Else
  23.             MessageBox.Show("ConnectionManager is null.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  24.         End If
  25.     End Sub

  26.     '// ----------------------------------------------------------------------------------------------------
  27.     '// ทดสอบการเชื่อมต่อและทำการบันทึกข้อมูลลงใน Registry
  28.     '// ----------------------------------------------------------------------------------------------------
  29.     Private Sub btnConnection_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
  30.         '// บันทึกค่าใหม่
  31.         MySQLConnectionManager.Host = txtHost.Text.Trim()
  32.         MySQLConnectionManager.DBName = txtDBName.Text.Trim()
  33.         MySQLConnectionManager.DBPort = txtDBPort.Text.Trim()
  34.         MySQLConnectionManager.DBUsername = txtDBUsername.Text.Trim()
  35.         MySQLConnectionManager.DBPassword = txtDBPassword.Text.Trim()
  36.         If Not MySQLConnectionManager.TestConnection() Then
  37.             MessageBox.Show("Connection Manager is not initialized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  38.             Return
  39.         Else
  40.             '// บันทึกลง Registry
  41.             MySQLConnectionManager.SaveToRegistry()
  42.             MessageBox.Show("บันทึกการตั้งค่าเรียบร้อยแล้ว", "สำเร็จ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  43.             Me.Close()
  44.         End If
  45.     End Sub

  46.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  47.         Me.Close()
  48.     End Sub

  49.     Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtHost.KeyPress, txtDBName.KeyPress, txtDBPassword.KeyPress, txtDBUsername.KeyPress, txtDBPort.KeyPress
  50.         '// ตรวจสอบว่าปุ่มที่กดคือ Enter
  51.         If Asc(e.KeyChar) = Keys.Enter Then
  52.             e.Handled = True '// ยกเลิกการประมวลผลปุ่ม Enter
  53.             SendKeys.Send("{TAB}") '// ส่งคีย์ Tab เพื่อเปลี่ยนโฟกัสไปยัง Control ถัดไป
  54.         End If
  55.     End Sub
  56. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของฟอร์มหลัก เพื่อแสดงผลข้อมูลตัวอย่างในตารางกริด ... frmMain.vb ...
  1. Imports MySql.Data.MySqlClient

  2. Public Class frmMain

  3.     Private clsDB As MySQLDataBase

  4.     Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  5.         '// โหลดค่าการตั้งค่าการเชื่อมต่อจาก Registry
  6.         MySQLConnectionManager.LoadFromRegistry()
  7.         '// ตรวจสอบว่ามีการเชื่อมต่อสำเร็จแล้วหรือไม่
  8.         If Not MySQLConnectionManager.IsConnected() Then
  9.             MessageBox.Show("การเชื่อมต่อฐานข้อมูลยังไม่พร้อม กรุณาตรวจสอบการเชื่อมต่อ", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
  10.             Return
  11.         End If
  12.         '// แสดงค่า Host, Database, และ Username ใน Statusbar
  13.         staHost.Text = "Host : " & MySQLConnectionManager.Host & "        "
  14.         staDatabase.Text = "Database : " & MySQLConnectionManager.DBName & "        "
  15.         '// ใช้ CurrUser ภายในคลาส MySQLUserInfo
  16.         staUsername.Text = "Username : " & CurrUser.Username & "        "

  17.         '// สร้าง Instance ของ clsDataBaseMySQL โดยส่ง Connection String ไป
  18.         clsDB = New MySQLDataBase(MySQLConnectionManager.GetConnectionString)
  19.         '// ทดสอบการเชื่อมต่อฐานข้อมูลผ่านคลาส clsDB (หากต้องการทดสอบ)
  20.         If Not clsDB.TestDBConnection() Then
  21.             MessageBox.Show("ไม่สามารถเชื่อมต่อฐานข้อมูลได้", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
  22.             Return
  23.         End If

  24.         '// ดึงข้อมูลจากฐานข้อมูล โดยมี Optional เป็น False (ไม่ต้องใส่ค่านี้ก็ได้) เพื่อให้แสดงผลออกมาทั้งหมด
  25.         Dim DT As DataTable = GetDataTable()
  26.         '// ตรวจสอบว่ามีข้อมูลหรือไม่
  27.         If DT IsNot Nothing AndAlso DT.Rows.Count > 0 Then
  28.             '// ผูกข้อมูลกับ DataGridView
  29.             dgvData.DataSource = DT
  30.             '// ตั้งค่าตารางกริด
  31.             Call SetupDataGridView()
  32.         Else
  33.             '// ถ้าไม่มีข้อมูล ให้เคลียร์ DataSource และแถวทั้งหมด
  34.             dgvData.DataSource = Nothing
  35.             dgvData.Rows.Clear()
  36.             MessageBox.Show("ไม่พบข้อมูลในฐานข้อมูล", "แจ้งเตือน", MessageBoxButtons.OK, MessageBoxIcon.Information)
  37.         End If
  38.         lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
  39.     End Sub

  40.     '// ----------------------------------------------------------------------------------------------------------
  41.     '// blnSearch = True, Show that the search results.
  42.     '// blnSearch is set to False, Show all records.
  43.     '// ----------------------------------------------------------------------------------------------------------
  44.     Private Function GetDataTable(Optional ByVal blnSearch As Boolean = False) As DataTable
  45.         Dim strSQL As String = _
  46.             " SELECT tblemployee.EmployeePK, tblemployee.EmployeeID, tblemployee.Fullname, tblemployee.HireDate, " & _
  47.             " tblemployee.Salary, tblposition.PositionName, tbldepartment.DepartmentName " & _
  48.             " FROM tblposition INNER JOIN (tbldepartment INNER JOIN tblemployee ON " & _
  49.             " tbldepartment.DepartmentPK = tblemployee.DepartmentFK) ON tblposition.PositionPK = tblemployee.PositionFK "
  50.         '// blnSearch = True ก็คือการค้นหาข้อมูล ตามที่คีย์ใน TxtSearch.Text
  51.         If blnSearch Then
  52.             strSQL = strSQL & _
  53.                     " WHERE " & _
  54.                     " (EmployeeID " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  55.                     " Fullname " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  56.                     " PositionName " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  57.                     " DepartmentName " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  58.                     " Mobile " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  59.                     " Phone " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  60.                     " eMail " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  61.                     " LineID " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
  62.                     " FaceBookID " & " Like '%" & txtSearch.Text & "%'" & _
  63.                     ") ORDER BY EmployeePK "

  64.             '// แสดงผลทั้งหมด
  65.         Else
  66.             strSQL = strSQL & " ORDER BY EmployeePK "
  67.         End If
  68.         '// เรียกใช้งานไปยังคลาส MySQLDataBase.vb
  69.         Return clsDB.RecordToScreen(strSQL)
  70.     End Function

  71.     '// ----------------------------------------------------------------------------------------------------
  72.     '// การตั้งค่าให้กับตารางกริดในแบบการใช้โค้ด หรือ Run Time
  73.     '// ----------------------------------------------------------------------------------------------------
  74.     Private Sub SetupDataGridView()
  75.         With dgvData
  76.             '// ตั้งค่าพื้นฐานของ DataGridView
  77.             .RowHeadersVisible = False
  78.             .AllowUserToAddRows = False
  79.             .AllowUserToDeleteRows = False
  80.             .AllowUserToResizeRows = False
  81.             .MultiSelect = False
  82.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  83.             .ReadOnly = True
  84.             .Font = New Font("Tahoma", 11, FontStyle.Regular)
  85.             .RowTemplate.MinimumHeight = 27
  86.             .RowTemplate.Height = 27
  87.             .ColumnHeadersHeight = 32
  88.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill '// ปรับขนาดคอลัมน์ให้เหมาะสม
  89.             .EnableHeadersVisualStyles = False  '// Accept color background changes.
  90.             .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
  91.         End With
  92.         '// ปรับแต่งการแสดงผล Header ของตารางกริด
  93.         With dgvData.ColumnHeadersDefaultCellStyle
  94.             .BackColor = Color.Navy
  95.             .ForeColor = Color.Black '// Color.White
  96.             .Font = New Font("Tahoma", 11, FontStyle.Bold)
  97.         End With
  98.         '//
  99.         '// ปรับแต่งคอลัมน์ EmployeePK (ซ่อนคอลัมน์)
  100.         With dgvData.Columns("EmployeePK")
  101.             .HeaderText = "EmployeePK"
  102.             .Visible = False '// ซ่อนคอลัมน์
  103.         End With
  104.         '// ปรับแต่งคอลัมน์ EmployeeID
  105.         With dgvData.Columns("EmployeeID")
  106.             .HeaderText = "รหัสพนักงาน"
  107.             .ReadOnly = True
  108.         End With
  109.         '// ปรับแต่งคอลัมน์ Fullname
  110.         With dgvData.Columns("Fullname")
  111.             .HeaderText = "ชื่อ-นามสกุล"
  112.             .ReadOnly = True
  113.         End With
  114.         '// ปรับแต่งคอลัมน์ PositionName
  115.         With dgvData.Columns("PositionName")
  116.             .HeaderText = "ตำแหน่ง"
  117.             .ReadOnly = True
  118.         End With
  119.         '// ปรับแต่งคอลัมน์ DepartmentName
  120.         With dgvData.Columns("DepartmentName")
  121.             .HeaderText = "แผนก"
  122.             .ReadOnly = True
  123.         End With
  124.         '// ปรับแต่งคอลัมน์ Salary
  125.         With dgvData.Columns("Salary")
  126.             .HeaderText = "เงินเดือน"
  127.             .DefaultCellStyle.Format = "N2" '// จัดรูปแบบเป็นตัวเลขทศนิยม 2 ตำแหน่ง
  128.             .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
  129.             .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight '// จัดชิดขวา
  130.             .ReadOnly = True
  131.         End With
  132.         '// ปรับแต่งคอลัมน์ HireDate
  133.         With dgvData.Columns("HireDate")
  134.             .HeaderText = "วันที่เริ่มงาน"
  135.             .DefaultCellStyle.Format = "dd/MM/yyyy" '// จัดรูปแบบวันที่
  136.             .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
  137.             .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight '// จัดชิดขวา
  138.             .ReadOnly = True
  139.         End With
  140.         For iCol = 0 To dgvData.Columns.Count - 1
  141.             '// Calculates odd and even numbers. If any integer divide by 2, then answer 1 is odd number.
  142.             If iCol Mod 2 = 1 Then
  143.                 dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.Gold
  144.                 '// Integer divide by 2, then answer 1 is Even number.
  145.             Else
  146.                 dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.LightGoldenrodYellow
  147.             End If
  148.         Next
  149.     End Sub

  150.     '// ----------------------------------------------------------------------------------------------------
  151.     '// การแสดงผลข้อมูลออกมาทั้งหมด
  152.     '// ----------------------------------------------------------------------------------------------------
  153.     Private Sub btnRefresh_Click(sender As Object, e As System.EventArgs) Handles btnRefresh.Click
  154.         '// แสดงผลข้อมูลทั้งหมด
  155.         dgvData.DataSource = GetDataTable(False)
  156.         lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
  157.         txtSearch.Focus()
  158.     End Sub

  159.     Private Sub txtSearch_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtSearch.KeyPress
  160.         '// ลบอักขระที่ไม่พึงประสงค์ออกจากช่องค้นหา เช่น ', %, *
  161.         Call RemoveUndesirableCharacters()
  162.         '// หากช่องค้นหาว่างเปล่า ให้ยกเลิกการทำงาน
  163.         If String.IsNullOrWhiteSpace(txtSearch.Text) Then Exit Sub
  164.         '// เมื่อกด Enter (ASCII Code = 13)
  165.         If e.KeyChar = Chr(13) Then
  166.             '// ปิดเสียง Beep เมื่อกด Enter
  167.             e.Handled = True
  168.             '// เรียกใช้งานฟังก์ชันค้นหาข้อมูล
  169.             Call SearchAndDisplayData()
  170.         End If
  171.     End Sub

  172.     '''// <summary>
  173.     '''// ลบอักขระที่ไม่พึงประสงค์ออกจากช่องค้นหา
  174.     '''// </summary>
  175.     Private Sub RemoveUndesirableCharacters()
  176.         txtSearch.Text = txtSearch.Text.Trim.Replace("'", "").Replace("%", "").Replace("*", "")
  177.         txtSearch.SelectionStart = txtSearch.Text.Length '// ย้ายเคอร์เซอร์ไปท้ายข้อความ
  178.     End Sub

  179.     '''// <summary>
  180.     '''// ค้นหาข้อมูลและแสดงผลใน DataGridView
  181.     '''// </summary>
  182.     Private Sub SearchAndDisplayData()
  183.         '// ดึงข้อมูลจากฐานข้อมูลตามคำค้นหา
  184.         dgvData.DataSource = GetDataTable(True)
  185.         '// อัปเดตจำนวนรายการที่พบ
  186.         lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
  187.         '// ล้างข้อความในช่องค้นหา
  188.         txtSearch.Clear()
  189.     End Sub

  190.     Private Sub frmMain_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  191.         Me.Dispose()
  192.         GC.SuppressFinalize(Me)
  193.         Application.Exit()
  194.     End Sub

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

ส่วนของคลาส (Class) ในการติดต่อกับ MySQL Server ... MySQLConnectManager.vb ...
  1. Imports Microsoft.Win32
  2. Imports MySql.Data.MySqlClient

  3. Public Class MySQLConnectionManager
  4.     '// ตัวแปรสำหรับเก็บสถานะการเชื่อมต่อ
  5.     Private Shared _isConnected As Boolean = False
  6.     '// ----------------------------------------------------------------------------------------------------
  7.     '// ประกาศตัวแปรสำหรับเก็บค่า Connection String
  8.     Public Shared Host As String
  9.     Public Shared DBName As String
  10.     Public Shared DBPort As String
  11.     Public Shared DBUsername As String
  12.     Public Shared DBPassword As String
  13.     '// พาธใน Registry ที่จะใช้เก็บข้อมูล
  14.     Private Const RegistryPath As String = "SOFTWARE\VB and VBA Program Settings\MySQLConnection\ConfigDB"

  15.     '// ค่า Default สำหรับ Connection String
  16.     Private Const DefaultHost As String = "localhost"
  17.     Private Const DefaultDBName As String = "payroll"
  18.     Private Const DefaultDBPort As String = "3306"
  19.     Private Const DefaultDBUsername As String = "USER"  '// เปลี่ยนด้วย
  20.     '// ปกติไม่ควรนำรหัสผ่านมาเก็บไว้ หรือหากต้องการจะใช้จริงๆก็ควรจะเข้ารหัสเอาไว้ก่อนด้วย
  21.     Private Const DefaultDBPassword As String = "PASSWORD"  '// เปลี่ยนด้วย

  22.     '// ----------------------------------------------------------------------------------------------------
  23.     '// เมธอดสำหรับบันทึกค่าลงใน Registry
  24.     '// ----------------------------------------------------------------------------------------------------
  25.     Public Shared Sub SaveToRegistry()
  26.         Dim RegistryKey As RegistryKey = Registry.CurrentUser.CreateSubKey(RegistryPath)
  27.         Try
  28.             RegistryKey.SetValue("Host", Host)
  29.             RegistryKey.SetValue("DBName", DBName)
  30.             RegistryKey.SetValue("DBPort", DBPort)
  31.             RegistryKey.SetValue("DBUsername", DBUsername)
  32.             RegistryKey.SetValue("DBPassword", DBPassword)
  33.         Finally
  34.             RegistryKey.Close()
  35.         End Try
  36.     End Sub

  37.     '// ----------------------------------------------------------------------------------------------------
  38.     '// เมธอดสำหรับอ่านค่าจาก Registry
  39.     '// ----------------------------------------------------------------------------------------------------
  40.     Public Shared Sub LoadFromRegistry()
  41.         Dim RegistryKey As RegistryKey = Registry.CurrentUser.OpenSubKey(RegistryPath)
  42.         If RegistryKey IsNot Nothing Then
  43.             Try
  44.                 '// อ่านค่าจาก Registry (ถ้ามี)
  45.                 Host = RegistryKey.GetValue("Host", DefaultHost).ToString()
  46.                 DBName = RegistryKey.GetValue("DBName", DefaultDBName).ToString()
  47.                 DBPort = RegistryKey.GetValue("DBPort", DefaultDBPort).ToString()
  48.                 DBUsername = RegistryKey.GetValue("DBUsername", DefaultDBUsername).ToString()
  49.                 DBPassword = RegistryKey.GetValue("DBPassword", DefaultDBPassword).ToString()
  50.             Finally
  51.                 RegistryKey.Close()
  52.             End Try
  53.         Else
  54.             '// หากไม่พบคีย์ใน Registry ให้ใช้ค่า Default
  55.             Host = DefaultHost
  56.             DBName = DefaultDBName
  57.             DBPort = DefaultDBPort
  58.             DBUsername = DefaultDBUsername
  59.             DBPassword = DefaultDBPassword
  60.         End If
  61.     End Sub

  62.     '// ----------------------------------------------------------------------------------------------------
  63.     '// เมธอดสำหรับการเชื่อมต่อ MySQL Server
  64.     '// ----------------------------------------------------------------------------------------------------
  65.     Public Shared Function GetConnectionString() As String
  66.         '// สร้างเมธอดที่ประกอบสตริงจาก Dictionary หรือ List ของพารามิเตอร์
  67.         Dim Parameters As New Dictionary(Of String, String) From {
  68.             {"Server", Host},
  69.             {"Database", DBName},
  70.             {"Port", DBPort},
  71.             {"User Id", DBUsername},
  72.             {"Password", DBPassword},
  73.             {"CharSet", "utf8"},
  74.             {"Connect Timeout", "30"},
  75.             {"Pooling", "True"},
  76.             {"Persist Security Info", "True"},
  77.             {"Connection Reset", "False"},
  78.             {"Default Command Timeout", "300"}
  79.         }
  80.         '// สร้าง Connection String จาก Dictionary เช่น "Database", "payroll"
  81.         Dim ConnectionString As String = String.Join(";", Parameters.Select(Function(p) p.Key & "=" & p.Value))
  82.         Return ConnectionString
  83.     End Function

  84.     '// เมธอดสำหรับทดสอบการเชื่อมต่อ
  85.     Public Shared Function TestConnection() As Boolean
  86.         Using Conn As New MySqlConnection(GetConnectionString())
  87.             Try
  88.                 Conn.Open()
  89.                 _isConnected = True '// ตั้งค่าสถานะการเชื่อมต่อสำเร็จ
  90.                 Return True
  91.             Catch ex As Exception
  92.                 _isConnected = False '// ตั้งค่าสถานะการเชื่อมต่อล้มเหลว
  93.                 Return False
  94.             End Try
  95.         End Using
  96.     End Function

  97.     '// เมธอดสำหรับรีเซ็ตสถานะการเชื่อมต่อ
  98.     Public Shared Sub ResetConnectionState()
  99.         _isConnected = False
  100.     End Sub

  101.     '// เมธอดสำหรับตรวจสอบสถานะการเชื่อมต่อ
  102.     Public Shared Function IsConnected() As Boolean
  103.         Return _isConnected
  104.     End Function

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

โค้ดในส่วนของคลาสที่จัดการกับตัวฐานข้อมูล ... MySQLDataBase.vb ...
  1. Imports MySql.Data.MySqlClient

  2. Public Class MySQLDataBase

  3.     Private ReadOnly _ConnectionString As String

  4.     '// Constructor สำหรับรับ Connection String
  5.     Public Sub New(ConnectionString As String)
  6.         _ConnectionString = ConnectionString
  7.     End Sub

  8.     '// ----------------------------------------------------------------------------------------------------
  9.     '// ฟังค์ชั่นที่ใช้งานร่วมกันเพื่อทำการแสดงผลข้อมูลบนหน้าจอ
  10.     '// หลักๆคือนำข้อมูลที่ได้จาก Sql มาแสดงผลในตารางกริด
  11.     '// คืนค่ากลับด้วย DataTable
  12.     '// ----------------------------------------------------------------------------------------------------
  13.     Public Function RecordToScreen(ByVal Sql As String) As DataTable
  14.         Dim dt As New DataTable()
  15.         Using Conn As New MySqlConnection(_ConnectionString)
  16.             Using cmd As New MySqlCommand(Sql, Conn)
  17.                 Try
  18.                     Conn.Open()
  19.                     '// MySqlDataReader :
  20.                     '// ใช้ cmd.ExecuteReader() เพื่อดึงข้อมูลจากฐานข้อมูลแบบ Row-by-Row
  21.                     '// MySqlDataReader เป็น Forward-only และ Read-only
  22.                     '// หมายความว่าเราสามารถอ่านข้อมูลได้ทีละแถวและไม่สามารถย้อนกลับไปยังแถวเดิมได้
  23.                     Using reader As MySqlDataReader = cmd.ExecuteReader()
  24.                         '// สร้างคอลัมน์ใน DataTable จากโครงสร้างของ DataReader
  25.                         For i As Integer = 0 To reader.FieldCount - 1
  26.                             dt.Columns.Add(reader.GetName(i), reader.GetFieldType(i))
  27.                         Next
  28.                         '// อ่านข้อมูลจาก DataReader และเพิ่มลงใน DataTable
  29.                         While reader.Read()
  30.                             Dim row As DataRow = dt.NewRow()
  31.                             For i As Integer = 0 To reader.FieldCount - 1
  32.                                 row(i) = reader(i)
  33.                             Next
  34.                             dt.Rows.Add(row)
  35.                         End While
  36.                     End Using
  37.                 Catch ex As Exception
  38.                     MessageBox.Show("เกิดข้อผิดพลาด: " & ex.Message, "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
  39.                     Return Nothing
  40.                 End Try
  41.             End Using
  42.         End Using
  43.         Return dt
  44.     End Function

  45.     '// --------------------------------------------------------------------------------
  46.     '// เมธอดร่วมกันที่ใช้ในการ Insert/Update/Delete SQL Statement
  47.     '// --------------------------------------------------------------------------------
  48.     Public Function DoSQL(ByVal Sql As String) As Boolean
  49.         DoSQL = False
  50.         '// ใช้ Using สำหรับ MySqlConnection
  51.         Using Conn As New MySqlConnection(_ConnectionString)
  52.             Try
  53.                 '// เปิดการเชื่อมต่อ
  54.                 Conn.Open()
  55.                 '// ใช้ Using สำหรับ MySqlCommand
  56.                 Using SQLCmd As New MySqlCommand(Sql, Conn)
  57.                     SQLCmd.CommandType = CommandType.Text
  58.                     SQLCmd.ExecuteNonQuery()
  59.                 End Using '// SQLCmd จะถูก Dispose โดยอัตโนมัติที่นี่
  60.                 '// การอัปเดตสำเร็จ
  61.                 DoSQL = True
  62.             Catch ex As Exception
  63.                 '// จัดการข้อผิดพลาด
  64.                 MessageBox.Show( _
  65.                     "Error Update DoSQL: " & _
  66.                     ex.Message, _
  67.                     "Error", _
  68.                     MessageBoxButtons.OK, MessageBoxIcon.Error)
  69.             End Try
  70.         End Using '// Conn จะถูกปิดโดยอัตโนมัติที่นี่
  71.     End Function

  72.     '// เมธอดสำหรับทดสอบการเชื่อมต่อ
  73.     Public Function TestDBConnection() As Boolean
  74.         Using Conn As New MySqlConnection(_ConnectionString)
  75.             Try
  76.                 Conn.Open()
  77.                 Return True
  78.             Catch ex As Exception
  79.                 Return False
  80.             End Try
  81.         End Using
  82.     End Function
  83. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของคลาสในการจัดการกับข้อมูลผู้ใช้ ... MySQLUserInfo.vb ...
  1. '// ------------------------------------------------------------------
  2. '// User-defined Class
  3. Public Class MySQLUserInfo
  4.     '// Primary Key of User
  5.     Public Property UserPK As Integer
  6.     '// Username or UserID
  7.     Public Property Username As String
  8.     '// Password
  9.     Public Property Password As String
  10.     '// Administrator is True
  11.     Public Property IsAdmin As Boolean
  12.     '// Completename
  13.     Public Property CompleteName As String
  14.     '// Time Stamp
  15.     Public Property TimeLogin As Date
  16. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของโมดูลการจัดการด้วยฟังค์ชั่นทั่วไป ... modFunction.vb ...
  1. Module modFunction
  2.     ' / --------------------------------------------------------------------------------
  3.     ' / Get my project path
  4.     ' / AppPath = C:\My Project\bin\debug
  5.     ' / Replace "\bin\debug" with ""
  6.     ' / Return : C:\My Project\
  7.     Function MyPath(AppPath As String) As String
  8.         '/ Return Value
  9.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  10.         '// If not found folder then put the \ (BackSlash ASCII Code = 92) at the end.
  11.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  12.     End Function

  13.     ' / Initialize English Language
  14.     Public Sub EnglishLanguage()
  15.         For Each Language As InputLanguage In InputLanguage.InstalledInputLanguages
  16.             If Language.Culture.TwoLetterISOLanguageName.Contains("en") = True Then
  17.                 InputLanguage.CurrentInputLanguage = Language
  18.             End If
  19.         Next
  20.     End Sub

  21.     ' / Initialize Thai Language
  22.     Public Sub ThaiLanguage()
  23.         For Each Language As InputLanguage In InputLanguage.InstalledInputLanguages
  24.             If Language.Culture.TwoLetterISOLanguageName.Contains("th") = True Then
  25.                 InputLanguage.CurrentInputLanguage = Language
  26.             End If
  27.         Next
  28.     End Sub

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

โค้ดในส่วนของโมดูลการประกาศตัวแปรแบบ Global ... modGlobalVariables.vb ... (ในโปรเจคนี้จะมองเห็นได้หมด) ...
  1. Module modGlobalVariables
  2.     '// ประกาศเป็น Global Variable สำหรับข้อมูลของผู้ใช้งาน
  3.     Public CurrUser As New MySQLUserInfo
  4. End Module
คัดลอกไปที่คลิปบอร์ด

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

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

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

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

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

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

GMT+7, 2025-3-12 11:42 , Processed in 0.162342 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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