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

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

[VB.NET] แจกฟรีโค้ดการสร้างไฟล์ MS Access ด้วย ADOX พร้อมกับการสร้าง และลบตารางข้อมูล

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

308

กระทู้

499

โพสต์

6025

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6025




แอดมินไปเดินส่องตำราต่างๆของการเขียนโปรแกรมในภาคภาษาไทย ล้วนแล้วแต่มักสอนให้เก็บข้อมูลลงในระดับ File Server เช่น MSSQL หรือ MySQL โดยส่วนตัวแอดมินคิดว่ามันใหญ่โตเกินไป ไม่เหมาะกับผู้ที่พึ่งจะเรียนรู้การเขียนโปรแกรม หรือการทำโปรเจคขนาดเล็กๆไปถึงขนาดกลาง ที่มีการเคลื่อนไหวของข้อมูลไม่มากสักเท่าไหร่ รวมไปถึงการติดตั้งที่ยุ่งยากอีกต่างหาก ดังนั้นระดับ File Base เช่น MS Access จึงเป็นหนึ่งทางเลือกที่เรานำมาใช้งาน วันนี้แอดมินจะมาขอนำเสนอ การสร้างไฟล์ MS Access ขึ้นมาด้วยการติดต่อกับ ADOX (ADO Extend) ซึ่งเราได้ใช้กันมาตั้งแต่ยุคสมัย VB6 แล้วครับ มาบัดนี้จะเอามันมาใช้ประโยชน์บน VB.NET ... แอ่นแอ๊นนนนน



เลือก Reference --> COM ... Microsoft ADO Ext. for DLL and Security แบบ TypeLib ...


มาดูโค้ดกันเถอะ ... โค้ดอาจจะดูรกๆไปสักกะหน่อย ก็เพราะแอดมินเจตนาแยกให้เห็นวิธีการทำงานของโค้ดในแต่ละส่วน และยังไม่ได้ใส่โค้ดในการเช็คว่ามีชื่อตาราง หรือชื่อฟิลด์อยู่แล้วหรือไม่ เอาไว้รอบหน้าล่ะกันครับ
  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. ' / Purpose: Create MS Access DataBase with VB.NET
  8. ' / Microsoft Visual Basic .NET (2010) + MS ACCESS 2003+
  9. ' /
  10. ' / This is open source code under @CopyLeft by Thongkorn Tubtimkrob.
  11. ' / You can modify and/or distribute without to inform the developer.
  12. ' / --------------------------------------------------------------------------------

  13. Public Class frmCreateDataBase

  14.     ' / --------------------------------------------------------------------------------
  15.     Private Sub btnCreateDB_Click(sender As System.Object, e As System.EventArgs) Handles btnCreateDB.Click
  16.         Dim strPathData As String = MyPath(Application.StartupPath) & "Sample.accdb"
  17.         '/ Check the Filename.
  18.         If Not System.IO.File.Exists(strPathData) Then
  19.             '// No database files. So it must be rebuilt.
  20.             If CreateAccessDataBase(strPathData) Then
  21.                 If CreateTable(strPathData, "tblSample") Then
  22.                     MessageBox.Show("DataBase & Table has successfull created.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  23.                     Call InitializeGrid()
  24.                     '// Create Sample data.
  25.                     Call FillData(strPathData, "tblSample")
  26.                 End If
  27.             End If

  28.             '// File already exist.
  29.         Else
  30.             MessageBox.Show("The database file already exists.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  31.             '// You can delete the table and recreate again.
  32.             Call DropTable(strPathData, "tblSample")    '// Ignore Error.
  33.             If CreateTable(strPathData, "tblSample") Then
  34.                 MessageBox.Show("Table has successfull created.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  35.                 Call InitializeGrid()
  36.                 '// Create Sample data.
  37.                 Call FillData(strPathData, "tblSample")
  38.             End If
  39.         End If
  40.     End Sub

  41.     ' / --------------------------------------------------------------------------------
  42.     ' / CREATE FILE MS ACCESS.
  43.     Public Function CreateAccessDataBase(ByVal DatabaseFullPath As String) As Boolean
  44.         CreateAccessDataBase = False
  45.         Dim MyCatalog As New ADOX.Catalog()
  46.         Try
  47.             Dim sCreateString As String
  48.             sCreateString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFullPath)
  49.             MyCatalog.Create(sCreateString)
  50.             'MessageBox.Show("DataBase Created.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  51.             MyCatalog = Nothing
  52.             CreateAccessDataBase = True

  53.         Catch ex As System.Runtime.InteropServices.COMException
  54.             CreateAccessDataBase = False
  55.             MessageBox.Show(ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Error)
  56.         End Try
  57.         '//
  58.     End Function

  59.     ' / --------------------------------------------------------------------------------
  60.     ' / CREATE TABLE.
  61.     Public Function CreateTable(ByVal DatabaseFullPath As String, ByVal TableName As String) As Boolean
  62.         CreateTable = False
  63.         Dim strCreate As String = _
  64.             "CREATE TABLE " & TableName & "(" & _
  65.             "PK Long," & _
  66.             "ID VarChar(25)," & _
  67.             "NumberField Integer," & _
  68.             "CurrencyField Currency," & _
  69.             "DateField Date," & _
  70.             "BooleanField YesNo" & _
  71.             ");"
  72.         Try
  73.             '// Create the empty table in the DB file
  74.             Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFullPath & ";Persist Security Info=True")
  75.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  76.             Dim Cmd As New OleDb.OleDbCommand(strCreate, Conn)
  77.             Cmd.ExecuteNonQuery()
  78.             'MessageBox.Show("Table Created.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  79.             Cmd.Dispose()
  80.             Conn.Close()
  81.             CreateTable = True

  82.         Catch ex As Exception
  83.             MessageBox.Show(ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Error)
  84.             CreateTable = False
  85.         End Try
  86.     End Function

  87.     ' / --------------------------------------------------------------------------------
  88.     ' / DROP TABLE
  89.     Public Function DropTable(ByVal DatabaseFullPath As String, ByVal TableName As String) As Boolean
  90.         Dim strDrop As String = "DROP TABLE " & TableName
  91.         Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFullPath & ";Persist Security Info=True")
  92.         If Conn.State = ConnectionState.Closed Then Conn.Open()
  93.         Dim Cmd As New OleDb.OleDbCommand(strDrop, Conn)
  94.         Try
  95.             Cmd.ExecuteNonQuery()
  96.             Cmd.Dispose()
  97.             Conn.Close()
  98.             Return True
  99.         Catch ex As Exception
  100.             MessageBox.Show(ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Error)
  101.             Return False
  102.         End Try
  103.     End Function

  104.     ' / --------------------------------------------------------------------------------
  105.     ' / SAMPLE DATA.
  106.     Private Sub FillData(ByVal DatabaseFullPath As String, ByVal TableName As String)
  107.         Dim DT As New DataTable
  108.         DT.Columns.Add("PK")
  109.         DT.Columns.Add("ID")
  110.         DT.Columns.Add("NumberField")
  111.         DT.Columns.Add("CurrencyField")
  112.         DT.Columns.Add("DateField")
  113.         DT.Columns.Add("BooleanField")
  114.         Dim RandomClass As New Random()
  115.         Dim DR As DataRow = DT.NewRow()
  116.         For i As Long = 0 To 19
  117.             DR = DT.NewRow()
  118.             DR(0) = i + 1
  119.             DR(1) = "ID" & i + 1
  120.             DR(2) = RandomClass.Next(1, 99999)
  121.             DR(3) = FormatNumber(RandomClass.Next(100, 1000) + RandomClass.NextDouble(), 2)
  122.             '// Random Date.
  123.             Dim d As Date = Date.Today
  124.             d = d.AddDays(RandomClass.Next(-30, 0))
  125.             DR(4) = FormatDateTime(d, DateFormat.ShortDate).ToString
  126.             '// Random Boolean.
  127.             DR(5) = RandomClass.Next(0, 2) > 0
  128.             DT.Rows.Add(DR)
  129.         Next
  130.         DataGridView1.DataSource = DT
  131.         Label1.Text = "Total : " & DT.Rows.Count.ToString("#,##") & " Records."
  132.         '// INSERT DATA FROM DATATABLE INTO MS ACCESS.
  133.         Try
  134.             Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFullPath & ";Persist Security Info=True"
  135.             Dim Conn As New OleDb.OleDbConnection(strConn)
  136.             Dim SQLStmt As String = "DELETE * FROM " & TableName
  137.             Dim Cmd As New OleDb.OleDbCommand
  138.             '// DELETE ALL PREVIOUS RECORDS.
  139.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  140.             Cmd = New OleDb.OleDbCommand(SQLStmt, Conn)
  141.             Cmd.ExecuteNonQuery()
  142.             Cmd.Dispose()
  143.             '//
  144.             SQLStmt = "SELECT PK, ID, NumberField, CurrencyField, DateField, BooleanField FROM " & TableName
  145.             Dim DA As New OleDb.OleDbDataAdapter(SQLStmt, Conn)
  146.             Dim CB = New OleDb.OleDbCommandBuilder(DA)
  147.             DA.Update(DT)
  148.             MessageBox.Show("Create sample data successfull.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  149.             CB.Dispose()
  150.             DA.Dispose()
  151.             DT.Dispose()
  152.             Conn.Close()

  153.         Catch ex As Exception
  154.             MessageBox.Show(ex.Message)
  155.         End Try
  156.     End Sub

  157.     ' / --------------------------------------------------------------------------------
  158.     '// Initialize DataGridView @Run Time
  159.     Private Sub InitializeGrid()
  160.         With DataGridView1
  161.             .RowHeadersVisible = False
  162.             .AllowUserToAddRows = False
  163.             .AllowUserToDeleteRows = False
  164.             .AllowUserToResizeRows = False
  165.             .MultiSelect = False
  166.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  167.             .ReadOnly = True
  168.             .Font = New Font("Tahoma", 9)
  169.             '/ Autosize Columns.
  170.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  171.             .AutoResizeColumns()
  172.             '/ Adjust Header Styles
  173.             With .ColumnHeadersDefaultCellStyle
  174.                 .BackColor = Color.Navy
  175.                 .ForeColor = Color.White
  176.                 .Font = New Font("Tahoma", 9, FontStyle.Bold)
  177.             End With
  178.         End With
  179.     End Sub

  180.     ' / --------------------------------------------------------------------------------
  181.     ' / Get my project path
  182.     ' / AppPath = C:\My Project\bin\debug
  183.     ' / Replace "\bin\debug" with ""
  184.     ' / Return : C:\My Project\
  185.     Function MyPath(ByVal AppPath As String) As String
  186.         '/ MessageBox.Show(AppPath);
  187.         AppPath = AppPath.ToLower()
  188.         '/ Return Value
  189.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "").Replace("\bin\x86\release", "")
  190.         '// If not found folder then put the \ (BackSlash) at the end.
  191.         If Microsoft.VisualBasic.Right(MyPath, 1) <> "" Then MyPath = MyPath & ""
  192.     End Function

  193.     Private Sub frmCreateDataBase_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  194.         Label1.Text = ""
  195.     End Sub

  196.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  197.         Me.Close()
  198.     End Sub

  199.     Private Sub frmCreateDataBase_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  200.         Me.Dispose()
  201.         Application.Exit()
  202.     End Sub

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


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



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

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

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

0

กระทู้

58

โพสต์

10

เครดิต

Member

Rank: 2

เครดิต
10
โพสต์ 2022-10-25 20:07:21 | ดูโพสต์ทั้งหมด

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

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

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

GMT+7, 2024-4-19 10:16 , Processed in 0.140964 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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