|

โค้ด 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 ...
- Imports MySql.Data.MySqlClient
- Imports Microsoft.Win32
- Imports System.IO
- Public Class frmLogin
- '// ----------------------------------------------------------------------------------------------------
- '// S T A R T . . . H E R E
- '// ----------------------------------------------------------------------------------------------------
- Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- '//
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// ล็อคอินเข้าสู่ระบบ
- '// ----------------------------------------------------------------------------------------------------
- Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
- '// การตรวจสอบค่าว่างสำหรับ TextBox ด้วยการใช้ Dictionary ในการจับคู่
- '// Key: TextBox, Value: ข้อความแจ้งเตือน
- '// สร้าง Dictionary สำหรับ TextBox และข้อความแจ้งเตือน
- Dim RequiredFields As New Dictionary(Of TextBox, String) From {
- {txtUsername, "Enter your Username."},
- {txtPassword, "Enter your Password."}
- }
- '// ตรวจสอบแต่ละฟิลด์ใน Dictionary
- For Each Field In RequiredFields
- If String.IsNullOrWhiteSpace(Field.Key.Text) Then
- MessageBox.Show(Field.Value, "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
- Field.Key.Focus()
- Return
- End If
- Next
- '// อ่านค่า Connection String จาก Registry (หากกรณีที่มีการเปลี่ยนแปลงค่าใน frmConnection.vb)
- MySQLConnectionManager.LoadFromRegistry()
- '// ตรวจสอบการ Connection ก่อนที่จะเข้าไปอ่านฐานข้อมูลใน Payroll
- If Not MySQLConnectionManager.TestConnection() Then
- MessageBox.Show("Connection Manager is not initialized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
- '// เปิดฟอร์มการตั้งค่า Connection
- frmConnection.ShowDialog()
- Return
- End If
- '// ตรวจสอบการ Connection ก่อนที่จะเข้าไปอ่านฐานข้อมูลใน Payroll
- Using Conn As New MySqlConnection(MySQLConnectionManager.GetConnectionString())
- Try
- Conn.Open()
- '// ตรวจสอบข้อมูลผู้ใช้ในฐานข้อมูล
- If ValidateUser(Conn, txtUsername.Text, txtPassword.Text) Then
- MessageBox.Show("เข้าสู่ระบบสำเร็จสมบูรณ์", "สำเร็จ", MessageBoxButtons.OK, MessageBoxIcon.Information)
- Me.Hide()
- Dim MainForm As New frmMain
- MainForm.ShowDialog()
- '// เมื่อฟอร์มหลักปิด ก็กลับมาปิดฟอร์มตัวมันเองด้วย
- Me.Close()
- Else
- MessageBox.Show("Username หรือ Password ไม่ถูกต้อง", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
- End If
- Catch ex As Exception
- MessageBox.Show("เกิดข้อผิดพลาด: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
- frmConnection.ShowDialog()
- End Try
- End Using
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// ตรวจสอบ Username และ Password ในตารางข้อมูล tblUser
- '// ----------------------------------------------------------------------------------------------------
- Private Function ValidateUser(ByVal Conn As MySqlConnection, ByVal username As String, ByVal password As String) As Boolean
- Dim query As String = "SELECT * FROM tblUser WHERE username = @username AND password = @password"
- Using cmd As New MySqlCommand(query, Conn)
- cmd.Parameters.AddWithValue("@username", username)
- cmd.Parameters.AddWithValue("@password", password)
- Using reader As MySqlDataReader = cmd.ExecuteReader()
- If reader.HasRows Then
- While reader.Read()
- '// เก็บข้อมูลการเข้าใช้งานของผู้ใช้ โดยประกาศเป็น Global Variable สำหรับข้อมูลของผู้ใช้งาน
- '// Public CurrUser As New MySQLUserInfo (อยู่ใน modGlobalVariables.vb)
- CurrUser.UserPK = CInt(reader("UserPK").ToString())
- CurrUser.Username = reader("Username").ToString()
- CurrUser.CompleteName = reader("CompleteName").ToString()
- CurrUser.TimeLogin = DateTime.Now() '// Time Stamp
- CurrUser.IsAdmin = CBool(reader("IsAdmin").ToString())
- End While
- Return True
- Else
- Return False
- End If
- End Using
- End Using
- End Function
- '// ----------------------------------------------------------------------------------------------------
- '// ตั้งค่า Connection
- '// ----------------------------------------------------------------------------------------------------
- Private Sub btnConnection_Click(sender As System.Object, e As System.EventArgs) Handles btnConnection.Click
- frmConnection.ShowDialog()
- End Sub
- Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
- Me.Close()
- End Sub
- Private Sub frmLogin_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
- Me.Dispose()
- GC.SuppressFinalize(Me)
- End Sub
- Private Sub txtUsername_GotFocus(sender As Object, e As System.EventArgs) Handles txtUsername.GotFocus
- Call EnglishLanguage()
- End Sub
- Private Sub txtUsername_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtUsername.KeyPress
- If Asc(e.KeyChar) = 13 Then
- e.Handled = True
- SendKeys.Send("{TAB}")
- End If
- End Sub
- Private Sub txtPassword_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtPassword.KeyPress
- If Asc(e.KeyChar) = 13 Then
- e.Handled = True
- Call btnLogin_Click(sender, e)
- End If
- End Sub
- Private Sub txtPassword_GotFocus(sender As Object, e As System.EventArgs) Handles txtPassword.GotFocus
- Call EnglishLanguage()
- End Sub
- End Class
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของการทำการเชื่อมต่อ MySQL Server ... frmConnection.vb ...
- Imports MySql.Data.MySqlClient
- Imports Microsoft.Win32
- Public Class frmConnection
- Private ConnectionManager As New MySQLConnectionManager()
- '// ----------------------------------------------------------------------------------------------------
- '// S T A R T ... H E R E
- '// ----------------------------------------------------------------------------------------------------
- Private Sub frmConnection_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- '// อ่านค่า Connection String จาก Registry
- MySQLConnectionManager.LoadFromRegistry()
- '// โหลดค่าจาก ConnectionManager
- Call LoadSettings()
- End Sub
- Private Sub LoadSettings()
- '// ตรวจสอบว่า ConnectionManager มีค่าหรือไม่
- If ConnectionManager IsNot Nothing Then
- txtHost.Text = MySQLConnectionManager.Host
- txtDBName.Text = MySQLConnectionManager.DBName
- txtDBPort.Text = MySQLConnectionManager.DBPort
- txtDBUsername.Text = MySQLConnectionManager.DBUsername
- txtDBPassword.Text = MySQLConnectionManager.DBPassword
- Else
- MessageBox.Show("ConnectionManager is null.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
- End If
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// ทดสอบการเชื่อมต่อและทำการบันทึกข้อมูลลงใน Registry
- '// ----------------------------------------------------------------------------------------------------
- Private Sub btnConnection_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
- '// บันทึกค่าใหม่
- MySQLConnectionManager.Host = txtHost.Text.Trim()
- MySQLConnectionManager.DBName = txtDBName.Text.Trim()
- MySQLConnectionManager.DBPort = txtDBPort.Text.Trim()
- MySQLConnectionManager.DBUsername = txtDBUsername.Text.Trim()
- MySQLConnectionManager.DBPassword = txtDBPassword.Text.Trim()
- If Not MySQLConnectionManager.TestConnection() Then
- MessageBox.Show("Connection Manager is not initialized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
- Return
- Else
- '// บันทึกลง Registry
- MySQLConnectionManager.SaveToRegistry()
- MessageBox.Show("บันทึกการตั้งค่าเรียบร้อยแล้ว", "สำเร็จ", MessageBoxButtons.OK, MessageBoxIcon.Information)
- Me.Close()
- End If
- End Sub
- Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
- Me.Close()
- End Sub
- Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtHost.KeyPress, txtDBName.KeyPress, txtDBPassword.KeyPress, txtDBUsername.KeyPress, txtDBPort.KeyPress
- '// ตรวจสอบว่าปุ่มที่กดคือ Enter
- If Asc(e.KeyChar) = Keys.Enter Then
- e.Handled = True '// ยกเลิกการประมวลผลปุ่ม Enter
- SendKeys.Send("{TAB}") '// ส่งคีย์ Tab เพื่อเปลี่ยนโฟกัสไปยัง Control ถัดไป
- End If
- End Sub
- End Class
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของฟอร์มหลัก เพื่อแสดงผลข้อมูลตัวอย่างในตารางกริด ... frmMain.vb ...
- Imports MySql.Data.MySqlClient
- Public Class frmMain
- Private clsDB As MySQLDataBase
- Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
- '// โหลดค่าการตั้งค่าการเชื่อมต่อจาก Registry
- MySQLConnectionManager.LoadFromRegistry()
- '// ตรวจสอบว่ามีการเชื่อมต่อสำเร็จแล้วหรือไม่
- If Not MySQLConnectionManager.IsConnected() Then
- MessageBox.Show("การเชื่อมต่อฐานข้อมูลยังไม่พร้อม กรุณาตรวจสอบการเชื่อมต่อ", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
- Return
- End If
- '// แสดงค่า Host, Database, และ Username ใน Statusbar
- staHost.Text = "Host : " & MySQLConnectionManager.Host & " "
- staDatabase.Text = "Database : " & MySQLConnectionManager.DBName & " "
- '// ใช้ CurrUser ภายในคลาส MySQLUserInfo
- staUsername.Text = "Username : " & CurrUser.Username & " "
- '// สร้าง Instance ของ clsDataBaseMySQL โดยส่ง Connection String ไป
- clsDB = New MySQLDataBase(MySQLConnectionManager.GetConnectionString)
- '// ทดสอบการเชื่อมต่อฐานข้อมูลผ่านคลาส clsDB (หากต้องการทดสอบ)
- If Not clsDB.TestDBConnection() Then
- MessageBox.Show("ไม่สามารถเชื่อมต่อฐานข้อมูลได้", "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
- Return
- End If
- '// ดึงข้อมูลจากฐานข้อมูล โดยมี Optional เป็น False (ไม่ต้องใส่ค่านี้ก็ได้) เพื่อให้แสดงผลออกมาทั้งหมด
- Dim DT As DataTable = GetDataTable()
- '// ตรวจสอบว่ามีข้อมูลหรือไม่
- If DT IsNot Nothing AndAlso DT.Rows.Count > 0 Then
- '// ผูกข้อมูลกับ DataGridView
- dgvData.DataSource = DT
- '// ตั้งค่าตารางกริด
- Call SetupDataGridView()
- Else
- '// ถ้าไม่มีข้อมูล ให้เคลียร์ DataSource และแถวทั้งหมด
- dgvData.DataSource = Nothing
- dgvData.Rows.Clear()
- MessageBox.Show("ไม่พบข้อมูลในฐานข้อมูล", "แจ้งเตือน", MessageBoxButtons.OK, MessageBoxIcon.Information)
- End If
- lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
- End Sub
- '// ----------------------------------------------------------------------------------------------------------
- '// blnSearch = True, Show that the search results.
- '// blnSearch is set to False, Show all records.
- '// ----------------------------------------------------------------------------------------------------------
- Private Function GetDataTable(Optional ByVal blnSearch As Boolean = False) As DataTable
- Dim strSQL As String = _
- " SELECT tblemployee.EmployeePK, tblemployee.EmployeeID, tblemployee.Fullname, tblemployee.HireDate, " & _
- " tblemployee.Salary, tblposition.PositionName, tbldepartment.DepartmentName " & _
- " FROM tblposition INNER JOIN (tbldepartment INNER JOIN tblemployee ON " & _
- " tbldepartment.DepartmentPK = tblemployee.DepartmentFK) ON tblposition.PositionPK = tblemployee.PositionFK "
- '// blnSearch = True ก็คือการค้นหาข้อมูล ตามที่คีย์ใน TxtSearch.Text
- If blnSearch Then
- strSQL = strSQL & _
- " WHERE " & _
- " (EmployeeID " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " Fullname " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " PositionName " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " DepartmentName " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " Mobile " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " Phone " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " eMail " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " LineID " & " Like '%" & txtSearch.Text & "%'" & " OR " & _
- " FaceBookID " & " Like '%" & txtSearch.Text & "%'" & _
- ") ORDER BY EmployeePK "
- '// แสดงผลทั้งหมด
- Else
- strSQL = strSQL & " ORDER BY EmployeePK "
- End If
- '// เรียกใช้งานไปยังคลาส MySQLDataBase.vb
- Return clsDB.RecordToScreen(strSQL)
- End Function
- '// ----------------------------------------------------------------------------------------------------
- '// การตั้งค่าให้กับตารางกริดในแบบการใช้โค้ด หรือ Run Time
- '// ----------------------------------------------------------------------------------------------------
- Private Sub SetupDataGridView()
- With dgvData
- '// ตั้งค่าพื้นฐานของ DataGridView
- .RowHeadersVisible = False
- .AllowUserToAddRows = False
- .AllowUserToDeleteRows = False
- .AllowUserToResizeRows = False
- .MultiSelect = False
- .SelectionMode = DataGridViewSelectionMode.FullRowSelect
- .ReadOnly = True
- .Font = New Font("Tahoma", 11, FontStyle.Regular)
- .RowTemplate.MinimumHeight = 27
- .RowTemplate.Height = 27
- .ColumnHeadersHeight = 32
- .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill '// ปรับขนาดคอลัมน์ให้เหมาะสม
- .EnableHeadersVisualStyles = False '// Accept color background changes.
- .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
- End With
- '// ปรับแต่งการแสดงผล Header ของตารางกริด
- With dgvData.ColumnHeadersDefaultCellStyle
- .BackColor = Color.Navy
- .ForeColor = Color.Black '// Color.White
- .Font = New Font("Tahoma", 11, FontStyle.Bold)
- End With
- '//
- '// ปรับแต่งคอลัมน์ EmployeePK (ซ่อนคอลัมน์)
- With dgvData.Columns("EmployeePK")
- .HeaderText = "EmployeePK"
- .Visible = False '// ซ่อนคอลัมน์
- End With
- '// ปรับแต่งคอลัมน์ EmployeeID
- With dgvData.Columns("EmployeeID")
- .HeaderText = "รหัสพนักงาน"
- .ReadOnly = True
- End With
- '// ปรับแต่งคอลัมน์ Fullname
- With dgvData.Columns("Fullname")
- .HeaderText = "ชื่อ-นามสกุล"
- .ReadOnly = True
- End With
- '// ปรับแต่งคอลัมน์ PositionName
- With dgvData.Columns("PositionName")
- .HeaderText = "ตำแหน่ง"
- .ReadOnly = True
- End With
- '// ปรับแต่งคอลัมน์ DepartmentName
- With dgvData.Columns("DepartmentName")
- .HeaderText = "แผนก"
- .ReadOnly = True
- End With
- '// ปรับแต่งคอลัมน์ Salary
- With dgvData.Columns("Salary")
- .HeaderText = "เงินเดือน"
- .DefaultCellStyle.Format = "N2" '// จัดรูปแบบเป็นตัวเลขทศนิยม 2 ตำแหน่ง
- .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
- .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight '// จัดชิดขวา
- .ReadOnly = True
- End With
- '// ปรับแต่งคอลัมน์ HireDate
- With dgvData.Columns("HireDate")
- .HeaderText = "วันที่เริ่มงาน"
- .DefaultCellStyle.Format = "dd/MM/yyyy" '// จัดรูปแบบวันที่
- .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
- .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight '// จัดชิดขวา
- .ReadOnly = True
- End With
- For iCol = 0 To dgvData.Columns.Count - 1
- '// Calculates odd and even numbers. If any integer divide by 2, then answer 1 is odd number.
- If iCol Mod 2 = 1 Then
- dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.Gold
- '// Integer divide by 2, then answer 1 is Even number.
- Else
- dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.LightGoldenrodYellow
- End If
- Next
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// การแสดงผลข้อมูลออกมาทั้งหมด
- '// ----------------------------------------------------------------------------------------------------
- Private Sub btnRefresh_Click(sender As Object, e As System.EventArgs) Handles btnRefresh.Click
- '// แสดงผลข้อมูลทั้งหมด
- dgvData.DataSource = GetDataTable(False)
- lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
- txtSearch.Focus()
- End Sub
- Private Sub txtSearch_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtSearch.KeyPress
- '// ลบอักขระที่ไม่พึงประสงค์ออกจากช่องค้นหา เช่น ', %, *
- Call RemoveUndesirableCharacters()
- '// หากช่องค้นหาว่างเปล่า ให้ยกเลิกการทำงาน
- If String.IsNullOrWhiteSpace(txtSearch.Text) Then Exit Sub
- '// เมื่อกด Enter (ASCII Code = 13)
- If e.KeyChar = Chr(13) Then
- '// ปิดเสียง Beep เมื่อกด Enter
- e.Handled = True
- '// เรียกใช้งานฟังก์ชันค้นหาข้อมูล
- Call SearchAndDisplayData()
- End If
- End Sub
- '''// <summary>
- '''// ลบอักขระที่ไม่พึงประสงค์ออกจากช่องค้นหา
- '''// </summary>
- Private Sub RemoveUndesirableCharacters()
- txtSearch.Text = txtSearch.Text.Trim.Replace("'", "").Replace("%", "").Replace("*", "")
- txtSearch.SelectionStart = txtSearch.Text.Length '// ย้ายเคอร์เซอร์ไปท้ายข้อความ
- End Sub
- '''// <summary>
- '''// ค้นหาข้อมูลและแสดงผลใน DataGridView
- '''// </summary>
- Private Sub SearchAndDisplayData()
- '// ดึงข้อมูลจากฐานข้อมูลตามคำค้นหา
- dgvData.DataSource = GetDataTable(True)
- '// อัปเดตจำนวนรายการที่พบ
- lblRecordCount.Text = "จำนวน : " & dgvData.RowCount & " รายการ"
- '// ล้างข้อความในช่องค้นหา
- txtSearch.Clear()
- End Sub
- Private Sub frmMain_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
- Me.Dispose()
- GC.SuppressFinalize(Me)
- Application.Exit()
- End Sub
- End Class
คัดลอกไปที่คลิปบอร์ด
ส่วนของคลาส (Class) ในการติดต่อกับ MySQL Server ... MySQLConnectManager.vb ...
- Imports Microsoft.Win32
- Imports MySql.Data.MySqlClient
- Public Class MySQLConnectionManager
- '// ตัวแปรสำหรับเก็บสถานะการเชื่อมต่อ
- Private Shared _isConnected As Boolean = False
- '// ----------------------------------------------------------------------------------------------------
- '// ประกาศตัวแปรสำหรับเก็บค่า Connection String
- Public Shared Host As String
- Public Shared DBName As String
- Public Shared DBPort As String
- Public Shared DBUsername As String
- Public Shared DBPassword As String
- '// พาธใน Registry ที่จะใช้เก็บข้อมูล
- Private Const RegistryPath As String = "SOFTWARE\VB and VBA Program Settings\MySQLConnection\ConfigDB"
- '// ค่า Default สำหรับ Connection String
- Private Const DefaultHost As String = "localhost"
- Private Const DefaultDBName As String = "payroll"
- Private Const DefaultDBPort As String = "3306"
- Private Const DefaultDBUsername As String = "USER" '// เปลี่ยนด้วย
- '// ปกติไม่ควรนำรหัสผ่านมาเก็บไว้ หรือหากต้องการจะใช้จริงๆก็ควรจะเข้ารหัสเอาไว้ก่อนด้วย
- Private Const DefaultDBPassword As String = "PASSWORD" '// เปลี่ยนด้วย
- '// ----------------------------------------------------------------------------------------------------
- '// เมธอดสำหรับบันทึกค่าลงใน Registry
- '// ----------------------------------------------------------------------------------------------------
- Public Shared Sub SaveToRegistry()
- Dim RegistryKey As RegistryKey = Registry.CurrentUser.CreateSubKey(RegistryPath)
- Try
- RegistryKey.SetValue("Host", Host)
- RegistryKey.SetValue("DBName", DBName)
- RegistryKey.SetValue("DBPort", DBPort)
- RegistryKey.SetValue("DBUsername", DBUsername)
- RegistryKey.SetValue("DBPassword", DBPassword)
- Finally
- RegistryKey.Close()
- End Try
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// เมธอดสำหรับอ่านค่าจาก Registry
- '// ----------------------------------------------------------------------------------------------------
- Public Shared Sub LoadFromRegistry()
- Dim RegistryKey As RegistryKey = Registry.CurrentUser.OpenSubKey(RegistryPath)
- If RegistryKey IsNot Nothing Then
- Try
- '// อ่านค่าจาก Registry (ถ้ามี)
- Host = RegistryKey.GetValue("Host", DefaultHost).ToString()
- DBName = RegistryKey.GetValue("DBName", DefaultDBName).ToString()
- DBPort = RegistryKey.GetValue("DBPort", DefaultDBPort).ToString()
- DBUsername = RegistryKey.GetValue("DBUsername", DefaultDBUsername).ToString()
- DBPassword = RegistryKey.GetValue("DBPassword", DefaultDBPassword).ToString()
- Finally
- RegistryKey.Close()
- End Try
- Else
- '// หากไม่พบคีย์ใน Registry ให้ใช้ค่า Default
- Host = DefaultHost
- DBName = DefaultDBName
- DBPort = DefaultDBPort
- DBUsername = DefaultDBUsername
- DBPassword = DefaultDBPassword
- End If
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// เมธอดสำหรับการเชื่อมต่อ MySQL Server
- '// ----------------------------------------------------------------------------------------------------
- Public Shared Function GetConnectionString() As String
- '// สร้างเมธอดที่ประกอบสตริงจาก Dictionary หรือ List ของพารามิเตอร์
- Dim Parameters As New Dictionary(Of String, String) From {
- {"Server", Host},
- {"Database", DBName},
- {"Port", DBPort},
- {"User Id", DBUsername},
- {"Password", DBPassword},
- {"CharSet", "utf8"},
- {"Connect Timeout", "30"},
- {"Pooling", "True"},
- {"Persist Security Info", "True"},
- {"Connection Reset", "False"},
- {"Default Command Timeout", "300"}
- }
- '// สร้าง Connection String จาก Dictionary เช่น "Database", "payroll"
- Dim ConnectionString As String = String.Join(";", Parameters.Select(Function(p) p.Key & "=" & p.Value))
- Return ConnectionString
- End Function
- '// เมธอดสำหรับทดสอบการเชื่อมต่อ
- Public Shared Function TestConnection() As Boolean
- Using Conn As New MySqlConnection(GetConnectionString())
- Try
- Conn.Open()
- _isConnected = True '// ตั้งค่าสถานะการเชื่อมต่อสำเร็จ
- Return True
- Catch ex As Exception
- _isConnected = False '// ตั้งค่าสถานะการเชื่อมต่อล้มเหลว
- Return False
- End Try
- End Using
- End Function
- '// เมธอดสำหรับรีเซ็ตสถานะการเชื่อมต่อ
- Public Shared Sub ResetConnectionState()
- _isConnected = False
- End Sub
- '// เมธอดสำหรับตรวจสอบสถานะการเชื่อมต่อ
- Public Shared Function IsConnected() As Boolean
- Return _isConnected
- End Function
- End Class
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของคลาสที่จัดการกับตัวฐานข้อมูล ... MySQLDataBase.vb ...
- Imports MySql.Data.MySqlClient
- Public Class MySQLDataBase
- Private ReadOnly _ConnectionString As String
- '// Constructor สำหรับรับ Connection String
- Public Sub New(ConnectionString As String)
- _ConnectionString = ConnectionString
- End Sub
- '// ----------------------------------------------------------------------------------------------------
- '// ฟังค์ชั่นที่ใช้งานร่วมกันเพื่อทำการแสดงผลข้อมูลบนหน้าจอ
- '// หลักๆคือนำข้อมูลที่ได้จาก Sql มาแสดงผลในตารางกริด
- '// คืนค่ากลับด้วย DataTable
- '// ----------------------------------------------------------------------------------------------------
- Public Function RecordToScreen(ByVal Sql As String) As DataTable
- Dim dt As New DataTable()
- Using Conn As New MySqlConnection(_ConnectionString)
- Using cmd As New MySqlCommand(Sql, Conn)
- Try
- Conn.Open()
- '// MySqlDataReader :
- '// ใช้ cmd.ExecuteReader() เพื่อดึงข้อมูลจากฐานข้อมูลแบบ Row-by-Row
- '// MySqlDataReader เป็น Forward-only และ Read-only
- '// หมายความว่าเราสามารถอ่านข้อมูลได้ทีละแถวและไม่สามารถย้อนกลับไปยังแถวเดิมได้
- Using reader As MySqlDataReader = cmd.ExecuteReader()
- '// สร้างคอลัมน์ใน DataTable จากโครงสร้างของ DataReader
- For i As Integer = 0 To reader.FieldCount - 1
- dt.Columns.Add(reader.GetName(i), reader.GetFieldType(i))
- Next
- '// อ่านข้อมูลจาก DataReader และเพิ่มลงใน DataTable
- While reader.Read()
- Dim row As DataRow = dt.NewRow()
- For i As Integer = 0 To reader.FieldCount - 1
- row(i) = reader(i)
- Next
- dt.Rows.Add(row)
- End While
- End Using
- Catch ex As Exception
- MessageBox.Show("เกิดข้อผิดพลาด: " & ex.Message, "ข้อผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error)
- Return Nothing
- End Try
- End Using
- End Using
- Return dt
- End Function
- '// --------------------------------------------------------------------------------
- '// เมธอดร่วมกันที่ใช้ในการ Insert/Update/Delete SQL Statement
- '// --------------------------------------------------------------------------------
- Public Function DoSQL(ByVal Sql As String) As Boolean
- DoSQL = False
- '// ใช้ Using สำหรับ MySqlConnection
- Using Conn As New MySqlConnection(_ConnectionString)
- Try
- '// เปิดการเชื่อมต่อ
- Conn.Open()
- '// ใช้ Using สำหรับ MySqlCommand
- Using SQLCmd As New MySqlCommand(Sql, Conn)
- SQLCmd.CommandType = CommandType.Text
- SQLCmd.ExecuteNonQuery()
- End Using '// SQLCmd จะถูก Dispose โดยอัตโนมัติที่นี่
- '// การอัปเดตสำเร็จ
- DoSQL = True
- Catch ex As Exception
- '// จัดการข้อผิดพลาด
- MessageBox.Show( _
- "Error Update DoSQL: " & _
- ex.Message, _
- "Error", _
- MessageBoxButtons.OK, MessageBoxIcon.Error)
- End Try
- End Using '// Conn จะถูกปิดโดยอัตโนมัติที่นี่
- End Function
- '// เมธอดสำหรับทดสอบการเชื่อมต่อ
- Public Function TestDBConnection() As Boolean
- Using Conn As New MySqlConnection(_ConnectionString)
- Try
- Conn.Open()
- Return True
- Catch ex As Exception
- Return False
- End Try
- End Using
- End Function
- End Class
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของคลาสในการจัดการกับข้อมูลผู้ใช้ ... MySQLUserInfo.vb ...
- '// ------------------------------------------------------------------
- '// User-defined Class
- Public Class MySQLUserInfo
- '// Primary Key of User
- Public Property UserPK As Integer
- '// Username or UserID
- Public Property Username As String
- '// Password
- Public Property Password As String
- '// Administrator is True
- Public Property IsAdmin As Boolean
- '// Completename
- Public Property CompleteName As String
- '// Time Stamp
- Public Property TimeLogin As Date
- End Class
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของโมดูลการจัดการด้วยฟังค์ชั่นทั่วไป ... modFunction.vb ...
- Module modFunction
- ' / --------------------------------------------------------------------------------
- ' / Get my project path
- ' / AppPath = C:\My Project\bin\debug
- ' / Replace "\bin\debug" with ""
- ' / Return : C:\My Project\
- Function MyPath(AppPath As String) As String
- '/ Return Value
- MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
- '// If not found folder then put the \ (BackSlash ASCII Code = 92) at the end.
- If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
- End Function
- ' / Initialize English Language
- Public Sub EnglishLanguage()
- For Each Language As InputLanguage In InputLanguage.InstalledInputLanguages
- If Language.Culture.TwoLetterISOLanguageName.Contains("en") = True Then
- InputLanguage.CurrentInputLanguage = Language
- End If
- Next
- End Sub
- ' / Initialize Thai Language
- Public Sub ThaiLanguage()
- For Each Language As InputLanguage In InputLanguage.InstalledInputLanguages
- If Language.Culture.TwoLetterISOLanguageName.Contains("th") = True Then
- InputLanguage.CurrentInputLanguage = Language
- End If
- Next
- End Sub
- End Module
คัดลอกไปที่คลิปบอร์ด
โค้ดในส่วนของโมดูลการประกาศตัวแปรแบบ Global ... modGlobalVariables.vb ... (ในโปรเจคนี้จะมองเห็นได้หมด) ...
- Module modGlobalVariables
- '// ประกาศเป็น Global Variable สำหรับข้อมูลของผู้ใช้งาน
- Public CurrUser As New MySQLUserInfo
- End Module
คัดลอกไปที่คลิปบอร์ด
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
|
ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง
คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน
x
|