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

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

[VB6/VB.NET] การ Compact และ Repair ไฟล์ฐานข้อมูล MS Access

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

310

กระทู้

501

โพสต์

6041

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6041




การใช้ฐานข้อมูล MS Access เมื่อเราใช้ไปสักระยะ ไฟล์ข้อมูลก็มักจะมีขนาดใหญ่โตขึ้นไปเรื่อยๆ ซึ่งอาจเป็นเพราะข้อมูลขยะหรือเกิดความผิดพลาด รวมไปถึงการจับจองพื้นที่ในการใช้งานด้วย ดังนั้นเราจึงต้องทำการบีบอัด (Compact) และซ่อมแซม (Repair) ไฟล์อย่างเป็นประจำ เพื่อป้องกันปัญหาที่อาจจะเกิดขึ้นในอนาคต สำหรับในการเขียนโปรแกรมด้วย VB6 และ VB.NET เราจำเป็นต้องใช้งาน Microsoft Jet and Replication Objects (JRO) ดังนั้นเราต้อง Add References เข้ามาก่อนการใช้งานด้วย ...


หลักการคิด ...
(1) เลือกไฟล์ MS Access เข้ามา
(2) เปลี่ยนชื่อไฟล์ MS Access เป็นชื่ออื่นก่อน เช่น RepairDB
(3) ทำการ Compact ไฟล์ พร้อมๆกับการทำสำเนา (Copy) และใช้ชื่อไฟล์ต้นฉบับ JRO.CompactDatabase(SourceConnection:=, Destconnection:=)
(4) ลบไฟล์ที่เปลี่ยนชื่อใหม่ในข้อ 2 ทิ้งไป


Add Reference สำหรับ VB6



Add Reference สำหรับ VB.NET (COM)



มาดูโค้ดของ VB6 ...
  1. ' / --------------------------------------------------------------------------
  2. ' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
  3. ' / eMail : thongkorn@hotmail.com
  4. ' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
  5. ' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
  6. ' / Facebook: https://www.facebook.com/commonindy (Worldwide)
  7. ' / MORE: http://www.g2gnet.com/webboard
  8. ' /
  9. ' / Purpose: Compact and Repair MS Access DataBase with VB6.
  10. ' / Microsoft Visual Basic 6.0 + MS Access
  11. ' /
  12. ' / This is open source code under @CopyLeft by Thongkorn/Common Tubtimkrob.
  13. ' / You can modify and/or distribute without to inform the developer.
  14. ' / --------------------------------------------------------------------------
  15. Option Explicit

  16. Private Sub cmdBrowse_Click()
  17.     On Error Resume Next
  18.     dlgDatabase.InitDir = App.Path
  19.     dlgDatabase.DialogTitle = " Compact and Repair database" ' Set the Common Dialog Title
  20.     dlgDatabase.Filter = "Microsoft Access Database (*.MDB) | *.MDB" ' Display only MDB files
  21.     dlgDatabase.CancelError = False ' Cancel all errors
  22.     dlgDatabase.ShowOpen ' Show Open Dialog
  23.     dlgDatabase.DefaultExt = "*.MDB" ' Set the default extension
  24.     txtFilePath = dlgDatabase.FileName ' Put the selected filename in the textbox
  25.     If txtFilePath.Text <> "" Then cmdCompactRepair.Enabled = True
  26. End Sub

  27. Private Sub cmdBrowse_KeyDown(KeyCode As Integer, Shift As Integer)
  28.     If KeyCode = vbKeyDown Or KeyCode = vbKeyRight Then SendKeys "{TAB}"
  29.     If KeyCode = vbKeyUp Or KeyCode = vbKeyLeft Then SendKeys "+{TAB}"
  30. End Sub


  31. Private Sub cmdCompactRepair_Click()
  32.     'On Error Resume Next
  33.     On Error GoTo ErrHandler
  34.     Dim JRO As New JRO.JetEngine
  35.     Dim xFile As String ' To capture the DIR return string
  36.     Dim strPassword As String
  37.     '// Put the password.
  38.     strPassword = ""

  39.     xFile = Dir(App.Path & "\RepairedDB.mdb") '/ See if the TempPath already exists

  40.     If xFile <> "" Then Kill App.Path & "\RepairedDB.mdb" '/ Check if the Temp file already exists
  41.    
  42.     ' เริ่มการ Compact
  43.     JRO.CompactDatabase _
  44.         "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & txtFilePath.Text & ";Jet OLEDB:Database Password=" & strPassword, _
  45.         "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\RepairedDB.MDB" & ";Jet OLEDB:Database Password=" & strPassword
  46.     '//
  47.     cmdCompactRepair.Enabled = False
  48.     cmdExit.Enabled = False
  49.     '// Kill the original DB
  50.     Kill txtFilePath
  51.     '// Rename the Repaired DB with the Original DB Name
  52.     Name App.Path & "\RepairedDB.mdb" As txtFilePath
  53.     cmdCompactRepair.Enabled = True
  54.     cmdExit.Enabled = True
  55.     MsgBox "ทำการซ่อมแซมไฟล์ฐานข้อมูลเรียบร้อยแล้ว", vbOKOnly + vbInformation, "รายงานสถานะ"
  56.    
  57.     'Unload Me

  58. ExitProc:
  59.     Exit Sub
  60.    
  61. ErrHandler:
  62.     If Err.Number = -2147217843 Or Left$(Err.Description, 20) = "Not a valid password" Then
  63.         MsgBox "มีรหัสผ่านป้องกันไฟล์ฐานข้อมูล หรือ รหัสผ่านไม่ถูกต้อง.", vbOKOnly + vbCritical, "ต้องการรหัสผ่าน - Password"
  64.         Resume ExitProc
  65.      
  66.     ElseIf Err.Number = -2147467259 Then
  67.         MsgBox "มีการเปิดไฟล์ฐานข้อมูล MS Access ค้างไว้ กรุณาปิดไฟล์ข้อมูลก่อนใช้งานด้วย.", vbOKOnly + vbCritical, "รายงานความผิดพลาด"
  68.         Resume ExitProc
  69.     Else
  70.         MsgBox "Compact Error: " & Err.Number & vbCrLf & Err.Description, vbOKOnly + vbExclamation, "รายงานความผิดพลาด"
  71.         Resume ExitProc
  72.     End If

  73. End Sub

  74. Private Sub cmdExit_Click()
  75.     Unload Me
  76. End Sub

  77. Private Sub Form_Load()
  78.     txtFilePath.Text = ""
  79.     If txtFilePath.Text = "" Then cmdCompactRepair.Visible = False
  80. End Sub

  81. Private Sub txtFilePath_Change()
  82.     If txtFilePath = "" Then
  83.         cmdCompactRepair.Visible = False
  84.     Else
  85.         cmdCompactRepair.Visible = True
  86.     End If
  87. End Sub

  88. Private Sub txtFilePath_KeyDown(KeyCode As Integer, Shift As Integer)
  89.     If KeyCode = vbKeyDown Then SendKeys "{TAB}"
  90.     If KeyCode = vbKeyUp Then SendKeys "+{TAB}"
  91. End Sub

  92. Private Sub txtFilePath_KeyPress(KeyAscii As Integer)
  93.     If KeyAscii = 13 Then
  94.         SendKeys "{TAB}"
  95.         KeyAscii = 0
  96.     End If
  97. End Sub

  98. Private Sub txtFilePath_LostFocus()
  99.     If txtFilePath = "" Then
  100.         cmdCompactRepair.Enabled = False
  101.     Else
  102.         cmdCompactRepair.Enabled = True
  103.     End If
  104. End Sub
คัดลอกไปที่คลิปบอร์ด


มาดูโค้ดของ VB.NET ...
  1. #Region "ABOUT"
  2. ' / --------------------------------------------------------------------------
  3. ' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
  4. ' / eMail : thongkorn@hotmail.com
  5. ' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
  6. ' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
  7. ' / Facebook: https://www.facebook.com/commonindy (Worldwide)
  8. ' / MORE: http://www.g2gnet.com/webboard
  9. ' /
  10. ' / Purpose: Compact and Repair MS Access DataBase with VB.NET (2010).
  11. ' / Microsoft Visual Basic .NET (2010) + MS Access
  12. ' /
  13. ' / This is open source code under @CopyLeft by Thongkorn/Common Tubtimkrob.
  14. ' / You can modify and/or distribute without to inform the developer.
  15. ' / --------------------------------------------------------------------------
  16. #End Region

  17. Imports System.IO

  18. Public Class frmCompact

  19.     '// Data Path
  20.     Dim DataPath As String = String.Empty
  21.     ' / --------------------------------------------------------------------------------
  22.     ' / Get my project path
  23.     ' / AppPath = C:\My Project\bin\debug
  24.     ' / Replace "\bin\debug" with ""
  25.     ' / Return : C:\My Project\
  26.     Function MyPath(AppPath As String) As String
  27.         '/ MessageBox.Show(AppPath);
  28.         AppPath = AppPath.ToLower()
  29.         '/ Return Value
  30.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  31.         '// If not found folder then put the \ (BackSlash) at the end.
  32.         If Microsoft.VisualBasic.Right(MyPath, 1) <> "" Then MyPath = MyPath & ""
  33.     End Function

  34.     ' / --------------------------------------------------------------------------
  35.     ' / Browse the MS Access and check File in use or not?
  36.     Private Sub btnBrowse_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
  37.         Dim OpenFile As New OpenFileDialog()
  38.         ' Specify the initial path, where I select the current project location.
  39.         OpenFile.InitialDirectory = MyPath(Application.StartupPath)
  40.         OpenFile.FileName = ""
  41.         ' Set to select only filter (MS Access file) (* .accdb)
  42.         OpenFile.Filter = "Microsoft Access (*.accdb)|*.accdb"

  43.         ' http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
  44.         ' http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx

  45.         Dim Res As System.Windows.Forms.DialogResult = OpenFile.ShowDialog()
  46.         '/ Press to cancel to exit sub.
  47.         If Res = System.Windows.Forms.DialogResult.Cancel Then Return

  48.         '// Check if the MS Access file is open or not.
  49.         If FileInUse(OpenFile.FileName) Then
  50.             MessageBox.Show("MS Access file is open, please close the file first.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  51.             Exit Sub
  52.         End If
  53.         ' Path and file names are displayed in the TextBox.
  54.         txtMDBLocation.Text = OpenFile.FileName
  55.         ' Path only
  56.         Dim Fi As New FileInfo(OpenFile.FileName)
  57.         DataPath = Fi.Directory.ToString
  58.         '// If you select root folder it must have \ (Backslash) ... "C:"
  59.         '// Others not have \ (Backslash) ... "C:\Data"
  60.         If Microsoft.VisualBasic.Right(DataPath, 1) <> "" Then DataPath = DataPath & ""
  61.     End Sub

  62.     ' / --------------------------------------------------------------------------
  63.     ' / Check File in use or open.
  64.     Public Function FileInUse(ByVal sFile As String) As Boolean
  65.         FileInUse = False
  66.         If System.IO.File.Exists(sFile) Then
  67.             Try
  68.                 Using F As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
  69.                     '// FileInUse = False
  70.                 End Using
  71.             Catch
  72.                 FileInUse = True
  73.             End Try
  74.         End If
  75.     End Function

  76.     ' / --------------------------------------------------------------------------
  77.     ' / Compact & Repair MS Access DataBase.
  78.     Private Sub btnCompact_Click(sender As System.Object, e As System.EventArgs) Handles btnCompact.Click
  79.         '// Check the file exist.
  80.         If txtMDBLocation.Text <> "" AndAlso File.Exists(txtMDBLocation.Text) Then
  81.             Try
  82.                 '// If File exists, delete it.
  83.                 If File.Exists(DataPath & "RepairDB.accdb") Then My.Computer.FileSystem.DeleteFile(DataPath & "RepairDB.accdb")
  84.                 My.Computer.FileSystem.RenameFile(txtMDBLocation.Text, "RepairDB.accdb")
  85.                 Dim JRO As New JRO.JetEngine
  86.                 ''/ Ref: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb237197(v=office.12)
  87.                 ' Format
  88.                 'JRO.CompactDatabase(SourceConnection:=, Destconnection:=)
  89.                 JRO.CompactDatabase( _
  90.                     "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DataPath & "RepairDB.accdb", _
  91.                     "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & txtMDBLocation.Text & ";Jet OLEDB:Engine Type=5" & _
  92.                     ";Jet OLEDB:Database Password=")
  93.                 My.Computer.FileSystem.DeleteFile(DataPath & "RepairDB.accdb")
  94.                 '//
  95.                 MessageBox.Show("Compact & Repair MS Access Successfully.")

  96.             Catch ex As Exception
  97.                 MessageBox.Show(ex.Message)
  98.             End Try
  99.         End If
  100.     End Sub

  101.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  102.         Me.Close()
  103.     End Sub

  104.     Private Sub frmCompact_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  105.         Me.Dispose()
  106.         Application.Exit()
  107.     End Sub

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




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


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

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

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

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

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

GMT+7, 2024-4-24 06:25 , Processed in 0.279978 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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