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

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

[VB.NET] โค้ดจับเวลาการแสดงผลข้อมูลการเชื่อมต่อ MySQL Server ด้วยวิธี Bound/UnBound Data

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

311

กระทู้

502

โพสต์

6048

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6048



แอดมินได้เคยอธิบายรายละเอียดวิธีการที่เรียกว่า Bound Data และ UnBound Data มาหลายรอบแล้ว ตั้งแต่ยุคสมัยของการใช้ VB6 ก็ไม่ขอกล่าวถึงซ้ำอีกน่ะครับ จากภาพเป็นเวลาที่ได้จากการเชื่อมต่อไปยัง DB Server ฟรีจาก remotemysql.com เป็นตารางเดี่ยวๆโดยมีข้อมูลอยู่ 10,000 รายการ แต่ค่าที่ได้ของเวลาก็จะขึ้นอยู่กับองค์ประกอบภายนอกด้วย เช่น สเปคคอมพิวเตอร์ และความเร็วอินเทอร์เน็ต ...

ก่อนจะรันโปรแกรม ต้อง Add Reference MySQL เข้ามาก่อน ... (อยู่ในไฟล์ต้นฉบับ)


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

  3. Public Class frmConnectMySQL
  4.     Private strFileINI As String

  5.     Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
  6.         If Trim(txtServer.Text.Length) = 0 Then
  7.             MessageBox.Show("Enter your DNS or IP Address.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  8.             txtServer.Focus()
  9.             Return
  10.         ElseIf Trim(txtDataBase.Text.Length) = 0 Then
  11.             MessageBox.Show("Enter your DataBase Name.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  12.             txtDataBase.Focus()
  13.             Return
  14.         ElseIf Trim(txtUsername.Text.Length) = 0 Then
  15.             MessageBox.Show("Enter your Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  16.             txtUsername.Focus()
  17.             Return
  18.         ElseIf Trim(txtPassword.Text.Length) = 0 Then
  19.             MessageBox.Show("Enter your Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  20.             txtPassword.Focus()
  21.             Return
  22.         End If
  23.         '// ConectMySQL in the modDataBase.vb
  24.         '// SERVER, DB Name, not keep User ID & Password for MySQL Server in INI File.
  25.         Cursor = Cursors.WaitCursor
  26.         If ConnectMySQL(Trim(txtServer.Text), Trim(txtDataBase.Text), Trim(txtUsername.Text), Trim(txtPassword.Text)) Then
  27.             MsgBox("Connection to MySQL Server successful.")
  28.             '// Save them to config.ini
  29.             WriteIni(strFileINI, "Config", "SERVER", Trim(txtServer.Text))
  30.             WriteIni(strFileINI, "Config", "DB", Trim(txtDataBase.Text))
  31.             WriteIni(strFileINI, "Config", "Username", Trim(txtUsername.Text))
  32.             WriteIni(strFileINI, "Config", "Password", Trim(txtPassword.Text))
  33.             '//
  34.             Cursor = Cursors.Default
  35.             frmBoundUnBoundData.Show()
  36.             Me.Hide()
  37.         End If
  38.     End Sub

  39.     Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
  40.         Me.Close()
  41.     End Sub

  42.     Private Sub frmConnectMySQL_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  43.         Me.Dispose()
  44.         Application.Exit()
  45.     End Sub

  46.     Private Sub SetupDataBase()
  47.         strFileINI = MyPath(Application.StartupPath) & "Config.ini"
  48.         '// Check if there is a Config.ini file.
  49.         If My.Computer.FileSystem.FileExists(strFileINI) Then
  50.             txtServer.Text = ReadIni(strFileINI, "Config", "SERVER", "")
  51.             txtDataBase.Text = ReadIni(strFileINI, "Config", "DB", "")
  52.             txtUsername.Text = ReadIni(strFileINI, "Config", "Username", "")
  53.             txtPassword.Text = ReadIni(strFileINI, "Config", "Password", "")
  54.             '// In case of not being found, start the new value.
  55.         Else
  56.             txtServer.Text = "remotemysql.com"
  57.             txtDataBase.Text = ""
  58.             txtUsername.Text = ""
  59.             txtPassword.Text = ""
  60.         End If
  61.     End Sub

  62.     Private Sub frmConnectMySQL_Load(sender As Object, e As System.EventArgs) Handles Me.Load
  63.         Call SetupDataBase()
  64.     End Sub
  65. 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 DS As DataSet
  7.     Public DR As MySqlDataReader
  8.     Public DA As MySqlDataAdapter
  9.     Public DT As DataTable
  10.     Public strSQL As String '// Major SQL
  11.     Public strStmt As String    '// Minor SQL

  12.     ' / --------------------------------------------------------------------------------
  13.     '// Connect to MySQL Server
  14.     Public Function ConnectMySQL(ByVal DNS As String, ByVal DB As String, ByVal UID As String, PWD As String) As Boolean
  15.         '// Use Dynamic DNS from No-IP.com
  16.         '// Server=localhost; User ID=YourUserID; Password=YourPassword; DataBase=YourDB
  17.         Dim strCon As String = _
  18.             " Server=" & DNS & "; " & _
  19.             " Database=" & DB & "; " & _
  20.             " User ID=" & UID & "; " & _
  21.             " Password=" & PWD & "; "
  22.         Conn = New MySqlConnection
  23.         Conn.ConnectionString = strCon
  24.         Try
  25.             Conn.Open()
  26.             Return True
  27.         Catch ex As Exception
  28.             MessageBox.Show(ex.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  29.             'Me.Close()
  30.             Return False
  31.         End Try
  32.     End Function

  33.     ' / --------------------------------------------------------------------------------
  34.     ' / Get my project path
  35.     ' / AppPath = C:\My Project\bin\debug
  36.     ' / Replace "\bin\debug" with ""
  37.     ' / Return : C:\My Project\
  38.     Function MyPath(AppPath As String) As String
  39.         '/ MessageBox.Show(AppPath);
  40.         AppPath = AppPath.ToLower()
  41.         '/ Return Value
  42.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  43.         '// If not found folder then put the \ (BackSlash has ASCII Code = 92) at the end.
  44.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  45.     End Function

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

มาดูโค้ดในส่วนของการทดสอบด้วยวิธี Bound และ UnBound Data ...
  1. Imports MySql.Data.MySqlClient

  2. Public Class frmBoundUnBoundData
  3.     '/ Start-Stop Timer
  4.     Private mTimeDouble As Double
  5.     Private sWatch As New Stopwatch()
  6.     '//
  7.     Private CheckMethod As Byte

  8.     ' / --------------------------------------------------------------------------
  9.     '/ BOUND DATA
  10.     Private Sub btnBound_Click(sender As System.Object, e As System.EventArgs) Handles btnBound.Click
  11.         CheckMethod = 1
  12.         Label3.Text = "Bound Data"
  13.         sWatch.Reset()
  14.         sWatch.Start()
  15.         Cursor = Cursors.WaitCursor
  16.         GridView1.DataSource = Nothing
  17.         '// START
  18.         Try
  19.             '// Open connection
  20.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  21.             DA = New MySqlDataAdapter("SELECT * FROM mytable ORDER BY pk", Conn)
  22.             DS = New DataSet
  23.             DA.Fill(DS, "MyTest")
  24.             Me.GridView1.DataSource = DS.Tables("MyTest").DefaultView
  25.             Call SetupDataGridView(GridView1)
  26.         Catch ex As Exception
  27.             MessageBox.Show(ex.Message)
  28.         End Try
  29.         DS.Dispose()
  30.         DA.Dispose()
  31.         '//
  32.         Cursor = Cursors.Default
  33.         sWatch.Stop()
  34.         mTimeDouble = sWatch.ElapsedMilliseconds * 0.001
  35.         txtBoundTime.Text = mTimeDouble.ToString
  36.         txtRecordCount.Text = String.Format(GridView1.Rows.Count, "N2")
  37.     End Sub

  38.     ' / --------------------------------------------------------------------------
  39.     '/ UNBOUND DATA
  40.     Private Sub btnUnBound_Click(sender As System.Object, e As System.EventArgs) Handles btnUnBound.Click
  41.         CheckMethod = 2
  42.         Label3.Text = "UnBound Data"
  43.         GridView1.DataSource = Nothing
  44.         Call SetupDataGridView(GridView1)

  45.         sWatch.Reset()
  46.         sWatch.Start()
  47.         Cursor = Cursors.WaitCursor
  48.         '// START
  49.         Dim tbl As New DataTable
  50.         Try
  51.             tbl = New DataTable
  52.             tbl.Columns.Add("PK", GetType(Long))
  53.             tbl.Columns.Add("ID", GetType(String))
  54.             tbl.Columns.Add("NumberField", GetType(Decimal))
  55.             tbl.Columns.Add("DoubleField", GetType(Double))
  56.             tbl.Columns.Add("MyDateField", GetType(Date))
  57.             '// Open connection
  58.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  59.             Cmd = New MySqlCommand("SELECT * FROM mytable ORDER BY pk", Conn)
  60.             DR = Cmd.ExecuteReader
  61.             While DR.Read()
  62.                 If DR.HasRows Then
  63.                     tbl.Rows.Add(New Object() { _
  64.                             Val(DR.Item("PK").ToString), _
  65.                             DR.Item("ID").ToString, _
  66.                             DR.Item("NumberField").ToString, _
  67.                             DR.Item("DoubleField").ToString, _
  68.                             DR.Item("MyDateField").ToString _
  69.                         })
  70.                 End If
  71.             End While
  72.             DR.Close()
  73.             Cmd.Dispose()
  74.             GridView1.DataSource = tbl
  75.         Catch ex As Exception
  76.             MessageBox.Show(ex.Message)
  77.         End Try
  78.         '//
  79.         Cursor = Cursors.Default
  80.         sWatch.Stop()
  81.         mTimeDouble = sWatch.ElapsedMilliseconds * 0.001
  82.         txtBoundTime.Text = mTimeDouble.ToString
  83.         txtRecordCount.Text = String.Format(GridView1.Rows.Count, "N2")
  84.     End Sub

  85.     Private Sub SetupDataGridView(ByRef DGV As DataGridView)
  86.         With DGV
  87.             .Columns.Clear()
  88.             .RowTemplate.Height = 22
  89.             .AllowUserToOrderColumns = True
  90.             .AllowUserToDeleteRows = False
  91.             .AllowUserToAddRows = False
  92.             .ReadOnly = True
  93.             .MultiSelect = False
  94.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  95.             .Font = New Font("Tahoma", 8)
  96.             If CheckMethod = 1 Then
  97.                 .AlternatingRowsDefaultCellStyle.BackColor = Color.Orange
  98.                 .DefaultCellStyle.SelectionBackColor = Color.LightSkyBlue
  99.             Else
  100.                 .AlternatingRowsDefaultCellStyle.BackColor = Color.LightYellow
  101.                 .DefaultCellStyle.SelectionBackColor = Color.LightBlue
  102.             End If
  103.             '/ Auto size column width of each main by sorting the field.
  104.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  105.             '.AutoResizeColumns()
  106.             '/
  107.             Dim PK As New DataGridViewTextBoxColumn
  108.             With PK
  109.                 .DataPropertyName = "pk"
  110.                 .Name = "pk"
  111.                 .HeaderText = "PK"
  112.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
  113.             End With
  114.             .Columns.Add(PK)
  115.             '/
  116.             Dim ID As New DataGridViewTextBoxColumn
  117.             With ID
  118.                 .DataPropertyName = "ID"
  119.                 .Name = "ID"
  120.                 .HeaderText = "ID"
  121.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
  122.             End With
  123.             .Columns.Add(ID)
  124.             '/
  125.             Dim NumberField As New DataGridViewTextBoxColumn
  126.             With NumberField
  127.                 .DataPropertyName = "NumberField"
  128.                 .Name = "NumberField1"
  129.                 .HeaderText = "NumberField"
  130.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
  131.             End With
  132.             .Columns.Add(NumberField)
  133.             '/
  134.             Dim DoubleField As New DataGridViewTextBoxColumn
  135.             With DoubleField
  136.                 .DataPropertyName = "DoubleField"
  137.                 .Name = "DoubleField"
  138.                 .HeaderText = "DoubleField"
  139.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
  140.             End With
  141.             .Columns.Add(DoubleField)
  142.             '/
  143.             Dim MyDateField As New DataGridViewTextBoxColumn
  144.             With MyDateField
  145.                 .DataPropertyName = "MyDateField"
  146.                 .Name = "MyDateField"
  147.                 .HeaderText = "MyDateField"
  148.                 .DefaultCellStyle.Format = "dd/MM/yyyy"
  149.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
  150.             End With
  151.             .Columns.Add(MyDateField)
  152.         End With
  153.     End Sub

  154.     Private Sub frmBoundUnBoundData_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  155.         If Conn.State = ConnectionState.Open Then Conn.Close()
  156.         Me.Dispose()
  157.         Application.Exit()
  158.     End Sub
  159. End Class
คัดลอกไปที่คลิปบอร์ด

มาดูโค้ดในส่วนของการจัดการ Initialized File ...
  1. Imports Microsoft.Win32

  2. Module modINI
  3.     ' / --------------------------------------------------------------------------------
  4.     ' / Initialized Management
  5.     Private Declare Unicode Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringW" ( _
  6.         ByVal lpApplicationName As String, _
  7.         ByVal lpKeyName As String, _
  8.         ByVal lpString As String, _
  9.         ByVal lpFileName As String _
  10.         ) As Int32

  11.     Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" ( _
  12.         ByVal lpApplicationName As String, _
  13.         ByVal lpKeyName As String, _
  14.         ByVal lpDefault As String, _
  15.         ByVal lpReturnedString As String, _
  16.         ByVal nSize As Int32, _
  17.         ByVal lpFileName As String _
  18.         ) As Int32
  19.     ' / --------------------------------------------------------------------------------

  20.     ' / --------------------------------------------------------------------------------
  21.     Public Sub WriteIni(ByVal iniFileName As String, ByVal Section As String, ByVal ParamName As String, ByVal ParamVal As String)
  22.         Dim Result As Integer = WritePrivateProfileString(Section, ParamName, ParamVal, iniFileName)
  23.     End Sub

  24.     Public Function ReadIni(ByVal IniFileName As String, ByVal Section As String, ByVal ParamName As String, ByVal ParamDefault As String) As String
  25.         Dim ParamVal As String = Space$(1024)
  26.         Dim LenParamVal As Long = GetPrivateProfileString(Section, ParamName, ParamDefault, ParamVal, Len(ParamVal), IniFileName)
  27.         ReadIni = Left$(ParamVal, LenParamVal)
  28.     End Function

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

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





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

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

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

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

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

GMT+7, 2024-4-24 21:45 , Processed in 0.127854 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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