[VB.NET] โค้ดการเชื่อมต่อฐานข้อมูล MySQL Server ด้วยการใช้งานคลาส และฟังค์ชั่น
http://www.g2gnet.com/webboard/images/vbnet/connectmysql.jpgสำหรับโค้ดชุดนี้แอดมินขอนำเสนอ การเชื่อมต่อฐานข้อมูล MySQL Server ด้วยการใช้งาน Class และ Function กันน่ะครับ ก็ขอให้ทุกๆท่านได้ศึกษาความเหมือน และความต่างกันเอาเองล่ะกัน แต่โดยปกติแอดมินจะถนัดในการใช้งานฟังค์ชั่นมากกว่าขอรับกระผม ... เนื่องจากว่าการล็อคอินจะต้องติดต่อกับ MySQL Server ให้ได้ก่อน หากติดต่อได้สำเร็จ ตัวแปรแบบ Public คือ blnConnect ก็จะถูกกำหนดให้เป็นจริง (True) ก่อนทำการล็อคอินเข้าสู่ระบบของ DataBase อีกรอบหนึ่งในตาราง tbluser ทำให้ไม่ต้องมาเสียเวลาในการ Connect เข้าสู่ Server อีกรอบ ในกรณีที่ผู้ใช้ใส่ชื่อหรือรหัสผ่านผิด ตารางข้อมูลตัวอย่างจะอยู่ในไฟล์โค้ดต้นฉบับเรียบร้อย ...
Add Reference ไฟล์ 2 ตัว ... Visual Basic Power Packs และ MySQL.Data ... http://www.g2gnet.com/webboard/images/vbnet/referencemysql.png
โค้ดหลักในหน้าจอล็อคอิน ...
Imports MySql.Data.MySqlClient
Public Class frmConnectMySQL
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
If Trim(txtServer.Text.Length) = 0 Then
MessageBox.Show("Enter your DNS or IP Address.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtServer.Focus()
Return
ElseIf Trim(txtDBName.Text.Length) = 0 Then
MessageBox.Show("Enter your DataBase Name.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtDBName.Focus()
Return
ElseIf Trim(txtDBUserName.Text.Length) = 0 Then
MessageBox.Show("Enter your DataBase Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtDBUserName.Focus()
Return
ElseIf Trim(txtDBPassword.Text.Length) = 0 Then
MessageBox.Show("Enter your DataBase Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtDBPassword.Focus()
Return
End If
'// Connecto to MySQL Server.
'// Select only one to connect.
Call ConnectClass()
'Call ConnectFunction()
End Sub
'// Calling to Class in clsConnectMySQL.
Private Sub ConnectClass()
'// Create Instance Name from clsConnectMySQL.vb
Dim MyConnect As New clsConnectMySQL
If Not blnConnect Then
With MyConnect
'// Assing the object property values
.ServerName = txtServer.Text
.DatabaseName = txtDBName.Text
.UserID = txtDBUserName.Text
.Password = txtDBPassword.Text
'// Connection String
Conn = .Connection
'// Connect to MySQL Server Successfull.
If Not IsNothing(Conn) Then
blnConnect = True
MessageBox.Show("Connection to MySQL Server successful.", "Login to Server", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(.ErrorMsg, "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
End With
End If
'// Login to User Table.
If blnConnect And LoginSystem() Then
MessageBox.Show("Operation Complete.")
'Me.Close()
End If
End Sub
'// Calling to Function in modDataBase.vb
Private Sub ConnectFunction()
'// blnConnect declare in modDataBase.vb and default valuse is FALSE.
If Not blnConnect Then
'// ConectMySQL in the modDataBase.vb
If ConnectMySQL(Trim(txtServer.Text), Trim(txtDBName.Text), txtDBUserName.Text.Trim, txtDBPassword.Text.Trim) Then
MessageBox.Show("Connection to MySQL Server successful.", "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Me.Cursor = Cursors.Default
Exit Sub
End If
End If
'// When successfully logged in to the server Next, check the logon table.
If blnConnect And LoginSystem() Then
MessageBox.Show("Operation Complete.")
'Me.Close()
End If
End Sub
' / --------------------------------------------------------------------------------
' / Login to User Table.
Private Function LoginSystem() As Boolean
LoginSystem = False
If Trim(txtUsername.Text.Length) = 0 Then
MessageBox.Show("Enter your Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtUsername.Focus()
Exit Function
ElseIf Trim(txtPassword.Text.Length) = 0 Then
MessageBox.Show("Enter your Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Focus()
Exit Function
End If
'//
Try
If Conn.State = ConnectionState.Closed Then Conn.Open()
Cmd = New MySqlCommand( _
" SELECT * FROM tbluser WHERE " & _
" Username = @UNAME AND Password = @PWD ", Conn)
Dim UsernameParam As New MySqlParameter("@UNAME", Me.txtUsername.Text)
Dim PasswordParam As New MySqlParameter("@PWD", Me.txtPassword.Text)
Cmd.Parameters.Add(UsernameParam)
Cmd.Parameters.Add(PasswordParam)
DR = Cmd.ExecuteReader()
'// Found data
If DR.HasRows Then
MessageBox.Show("You can logged into system.", "LOGON SYSTEM", MessageBoxButtons.OK, MessageBoxIcon.Information)
LoginSystem = True
Else
LoginSystem = False
MessageBox.Show("Enter your Username, Password is incorrect.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtUsername.Focus()
End If
DR.Close()
Cmd.Dispose()
'//
strSQL = _
" SELECT * FROM tbluser " & _
" WHERE Username = " & "'" & txtUsername.Text & "'"
DA = New MySqlDataAdapter(strSQL, Conn)
DS = New DataSet
DA.Fill(DS)
With DS.Tables(0)
'// modStructure.vb
CurrUser.USER_USERPK = Val(.Rows(0)("UserPK").ToString)
CurrUser.USER_USERNAME = .Rows(0)("Username").ToString()
CurrUser.USER_COMPLETENAME = .Rows(0)("CompleteName").ToString()
CurrUser.USER_TIMELOGIN = Now() ' Time Stamp
' True = Admin
CurrUser.USER_ISADMIN = CBool(.Rows(0)("IsAdmin").ToString)
End With
DS.Dispose()
DA.Dispose()
Conn.Dispose()
Conn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
'//
End Function
Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmConnectMySQL_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
If Not IsNothing(Conn) Then
If Conn.State = ConnectionState.Open Then Conn.Close()
Conn.Dispose()
Conn = Nothing
End If
Me.Dispose()
GC.SuppressFinalize(Me)
Application.Exit()
End Sub
Private Sub frmConnectMySQL_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
End Class
โค้ดในคลาส clsConnectMySQL.vb ...
Imports MySql.Data.MySqlClient
Public Class clsConnectMySQL
Private _Connection As New MySqlConnection
Private _ErrorMsg As String
Private _ServerName As String
Private _DatabaseName As String
Private _UserID As String
Private _Password As String
Public WriteOnly Property ServerName() As String
Set(ByVal value As String)
_ServerName = value
End Set
End Property
Public WriteOnly Property DatabaseName() As String
Set(ByVal value As String)
_DatabaseName = value
End Set
End Property
Public WriteOnly Property UserID() As String
Set(ByVal value As String)
_UserID = value
End Set
End Property
Public WriteOnly Property Password() As String
Set(ByVal value As String)
_Password = value
End Set
End Property
Public ReadOnly Property ErrorMsg() As String
Get
Return _ErrorMsg
End Get
End Property
Public Function Connection() As MySqlConnection
Connection = Nothing
Try
_Connection.ConnectionString = _
" Server = " & _ServerName & ";" & _
" Database = " & _DatabaseName & ";" & _
" User ID = " & _UserID & ";" & _
" Password = " & _Password & ";" & _
" Port = 3306;" & _
" CharSet = utf8; " & _
" Connect Timeout = 90; " & _
" Pooling = True; " & _
" Persist Security Info = False; " & _
" Connection Reset = False; " & _
" Default Command Timeout = 90; " & _
" Connection Lifetime = 0;"
_Connection.Open()
If _Connection.State = ConnectionState.Open Then _Connection.Close()
_Connection.Dispose()
Return _Connection
Catch ex As Exception
_ErrorMsg = ex.Message
End Try
End Function
End Class
โค้ดฟังค์ชั่นในโมดูล modDataBase.vb ...
Imports MySql.Data.MySqlClient
Module modDataBase
'// Declare variable one time but use many times.
Public Conn As MySqlConnection
Public Cmd As MySqlCommand
Public DR As MySqlDataReader
Public DA As MySqlDataAdapter
Public DS As DataSet
Public DT As DataTable
Public strSQL As String '// Major SQL
Public strStmt As String '// Minor SQL
'//
Public blnConnect As Boolean = False
' / --------------------------------------------------------------------------------
'// MySQL Server Connection Test with VB.NET (2010).
Public Function ConnectMySQL(ByVal SERVER As String, ByVal DB As String, ByVal UID As String, PWD As String) As Boolean
'// Server=localhost; DataBase=DB; User ID=YourUserID; Password=YourPassword;
Dim strCon As String = _
" Server = " & SERVER & "; " & _
" Database = " & DB & "; " & _
" User ID = " & UID & "; " & _
" Password = " & PWD & "; " & _
" Port = 3306; " & _
" CharSet = utf8; " & _
" Connect Timeout = 90; " & _
" Pooling = True; " & _
" Persist Security Info = True; " & _
" Connection Reset = False; " & _
" Default Command Timeout = 90; "
Conn = New MySqlConnection
Conn.ConnectionString = strCon
Try
Conn.Open()
ConnectMySQL = True
blnConnect = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ConnectMySQL = False
blnConnect = False
Finally
Conn.Dispose()
Conn.Close()
End Try
End Function
End Module
โค้ดโครงสร้าง (Structure) ในโมดูล modStructure.vb ... เก็บข้อมูลแบบโครงสร้างของ Users ...
Module modStructure
' / ------------------------------------------------------------------
' User-defined Types (UDTs)
Public Structure USER_INFO
' Primary Key of User
Dim USER_USERPK As Integer
' Username or UserID
Dim USER_USERNAME As String
' Password
Dim USER_PASSWORD As String
' Administrator is True
Dim USER_ISADMIN As Boolean
' Completename
Dim USER_COMPLETENAME As String
' Time Stamp
Dim USER_TIMELOGIN As Date
End Structure
' User-defined Types (UDTs)
Public Structure DB_INFO
' SERVER
Dim SERVER As String
Dim DB As String
Dim UID As String
Dim PWD As String
End Structure
' USER_INFO is a template, It can not be stored data.
' Assign a variable to a Data Structure (UDTs)
' Run through the series via CurrUser.
Public CurrUser As USER_INFO
' Example:
' CurrUser.USER_NAME ... Keep UserName string
' CurrUser.USER_ISADMIN ... Keep status true/false
' / ------------------------------------------------------------------
Public MyDB As DB_INFO
End Module
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
ขอบคุณคับ น้อมรับไปทดสอบ ขอบคุณครับ ^_^ ขอบคุณครับ แต่ทำไมของผม 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
ขอบคุณครับ อาจารย์ ขอบพระคุณครับ
หน้า:
[1]