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

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

[VB.NET] การสร้างฟิลด์ข้อมูล ตาราง และไฟล์ฐานข้อมูล SQLite ด้วยการเขียนโค้ด

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

309

กระทู้

500

โพสต์

6030

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6030



หลังจากได้ปล่อย โปรแกรมการพิมพ์ใบแจ้งค่าใช้จ่ายหอพัก/อพาร์ทเมนท์ (RoomPayment Lite Version) ซึ่งเป็นงานชิ้นแรกที่แอดมินได้ใช้ฐานข้อมูล SQLite สำหรับบทความนี้แอดมินจะมาแจกโค้ดในการสร้างฟิลด์ข้อมูล ตาราง และไฟล์ฐานข้อมูล SQLite แบบไดนามิค เพราะสำหรับโปรเจคดังกล่าวนั้น แอดมินต้องใช้การสร้างโครงสร้างต่างๆของ SQLite ด้วยการเขียนโค้ดเองทั้งหมด ตัว SQLite มีความโดดเด่นในเรื่องของจำนวนชนิดข้อมูลค่อนข้างน้อย คือมีแค่ Integer (เลขจำนวนเต็ม), Text (ตัวอักษร), Real (จำนวนจริง หรือเลขทศนิยม), Blob (เก็บข้อมูลแบบไบนารี่) และใน SQLite 3 ได้เพิ่ม Numeric เข้ามาอีกตัว รายละเอียดในเรื่องชนิดข้อมูลของ SQLite ศึกษาเพิ่มเติมได้จากที่นี่ ...

ดาวน์โหลด System.Data.SQLite สำหรับแอดมินใช้ Net Framework เวอร์ชั่น 4 ขนาด 64 บิต (sqlite-netFx40-setup-x64-2010-1.0.111.0.exe) ...

ก่อนที่จะเริ่มต้นลงโค้ด จะต้อง Add Reference System.Data.SQLite เข้ามาก่อน ... และต้องคัดลอกไฟล์ SQLite.Interop.DLL เอาไปไว้ที่โฟลเดอร์โปรเจค Bin\Debug ก่อนด้วย (สำหรับ Visual Studio เวอร์ชั่นที่สูงกว่า ก็จะเป็น Bin\x86\Debug)


ไปที่ Project Perperties เพื่อปรับขนาดจำนวนบิตให้เป็น Any CPU กรณี 64 บิต หากเป็น SQLite 32 บิตให้เลือก x86 ...



การใช้ DB Browser for SQLite ซึ่งเป็นของฟรีในการบริหารจัดการกับ SQLite (ดาวน์โหลดได้ที่นี่)


มาดูโค้ดฉบับเต็มกันเถอะ ...
  1. Imports System.Data.SQLite

  2. Public Class frmCreateSQLiteDB
  3.     Dim Conn As SQLiteConnection

  4.     ' / --------------------------------------------------------------------
  5.     ' / Close Connection
  6.     Private Sub frmCreateSQLiteDB_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  7.         Me.Dispose()
  8.         If Not IsNothing(Conn) Then
  9.             Conn.Close()
  10.             Conn.Dispose()
  11.         End If
  12.         Application.Exit()
  13.     End Sub

  14.     ' / --------------------------------------------------------------------
  15.     Private Sub frmCreateSQLiteDB_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  16.         With cmbFieldType
  17.             .Items.Add("INTEGER")
  18.             .Items.Add("TEXT")
  19.             .Items.Add("REAL")
  20.             .Items.Add("NUMERIC")
  21.         End With
  22.         cmbFieldType.SelectedIndex = 0
  23.         '/
  24.         Call InitializeGridInfo()
  25.         txtTableName.Text = "SampleTable"
  26.     End Sub

  27.     ' / --------------------------------------------------------------------
  28.     Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
  29.         If Trim(txtFieldName.Text) = "" Or Trim(txtFieldName.Text.Length) = 0 Then Return
  30.         For i = 0 To dgvInfo.RowCount - 1
  31.             If Trim(txtFieldName.Text).ToLower = LCase(dgvInfo.Rows(i).Cells(0).Value).ToString Then
  32.                 MessageBox.Show("มีฟิลด์ข้อมูลนี้อยู่ในตารางเรียบร้อยแล้ว.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  33.                 txtFieldName.Focus()
  34.                 Return
  35.             End If
  36.         Next
  37.         '// ตรวจคำสงวนที่นำมาใช้งานไม่ได้
  38.         Dim strReserve As String = "integer text real numeric blob"
  39.         If strReserve.Contains(Trim(txtFieldName.Text.ToLower)) Then
  40.             MessageBox.Show("เป็นคำสงวนไม่สามารถนำมาใช้ได้.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  41.             txtFieldName.Focus()
  42.             Return
  43.         End If
  44.         '//
  45.         dgvInfo.Rows.Add()
  46.         dgvInfo.Rows(dgvInfo.Rows.Count - 1).Cells(0).Value = Trim(txtFieldName.Text)
  47.         dgvInfo.Rows(dgvInfo.Rows.Count - 1).Cells(1).Value = cmbFieldType.Text
  48.         '//
  49.         txtFieldName.Clear()
  50.         txtFieldName.Focus()
  51.     End Sub

  52.     ' / --------------------------------------------------------------------
  53.     ' / Initialized settings for DataGridView @Run Time.
  54.     ' / --------------------------------------------------------------------
  55.     Private Sub InitializeGridInfo()
  56.         With dgvInfo
  57.             .RowHeadersVisible = True
  58.             .AllowUserToAddRows = False
  59.             .AllowUserToDeleteRows = False
  60.             .AllowUserToResizeRows = False
  61.             .MultiSelect = False
  62.             '// Need to modify each cell.
  63.             .SelectionMode = DataGridViewSelectionMode.CellSelect
  64.             .ReadOnly = False
  65.             '//
  66.             .Font = New Font("Tahoma", 9)
  67.             '/ Automatically set the width.
  68.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  69.             '/ Adjust Header Styles
  70.             With .ColumnHeadersDefaultCellStyle
  71.                 .BackColor = Color.Navy
  72.                 .ForeColor = Color.White
  73.                 .Font = New Font("Tahoma", 9, FontStyle.Bold)
  74.             End With
  75.         End With
  76.         '// Add Column.
  77.         Dim FieldName As New DataGridViewTextBoxColumn()
  78.         With FieldName
  79.             .HeaderText = "ชื่อฟิลด์ข้อมูล"
  80.             .ReadOnly = True
  81.         End With
  82.         dgvInfo.Columns.Add(FieldName)
  83.         '//
  84.         Dim FieldType As New DataGridViewComboBoxColumn()
  85.         With FieldType
  86.             .HeaderText = "ชนิดฟิลด์ข้อมูล"
  87.             .Items.Add("INTEGER")
  88.             .Items.Add("TEXT")
  89.             .Items.Add("REAL")
  90.             .Items.Add("NUMERIC")
  91.         End With
  92.         dgvInfo.Columns.Add(FieldType)
  93.         '//
  94.         Dim btnDelRow As New DataGridViewButtonColumn()
  95.         With btnDelRow
  96.             .HeaderText = ""
  97.             .Text = "ลบฟิลด์"
  98.             .Name = "btnDelRow"
  99.             .UseColumnTextForButtonValue = True
  100.             .Width = 80
  101.             .ReadOnly = True
  102.         End With
  103.         dgvInfo.Columns.Add(btnDelRow)

  104.     End Sub

  105.     ' / --------------------------------------------------------------------
  106.     Private Sub dgvInfo_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvInfo.CellClick
  107.         Select Case e.ColumnIndex
  108.             Case 2
  109.                 dgvInfo.Rows.Remove(dgvInfo.CurrentRow)
  110.         End Select
  111.     End Sub

  112.     Private Sub txtFieldName_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtFieldName.KeyPress
  113.         If e.KeyChar = Chr(13) Then
  114.             e.Handled = True
  115.             Call btnAdd_Click(sender, e)
  116.         End If
  117.     End Sub

  118.     ' / --------------------------------------------------------------------
  119.     Private Sub btnCreate_Click(sender As System.Object, e As System.EventArgs) Handles btnCreate.Click
  120.         If Trim(txtTableName.Text) = "" Or Trim(txtTableName.Text).Length = 0 Then
  121.             MessageBox.Show("กรุณาตั้งชื่อตารางก่อนด้วย.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  122.             Return
  123.         End If
  124.         If dgvInfo.RowCount = 0 Then
  125.             MessageBox.Show("ยังไม่มีรายการข้อมูล กรุณาทำการเพิ่มก่อนด้วย.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  126.             Return
  127.         End If
  128.         '//
  129.         Dim dlgSaveFile As New SaveFileDialog()
  130.         With dlgSaveFile
  131.             .Filter = "SQLite 3 (*.db3)|*.db3|SQLite (*.db)|*.db"
  132.             .Title = "บันทึกไฟล์ SQLite"
  133.             .DefaultExt = "db3"
  134.             .InitialDirectory = MyPath(Application.StartupPath)
  135.             .RestoreDirectory = True
  136.         End With
  137.         If dlgSaveFile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
  138.             Try
  139.                 '/ Check File Exist. If available, delete it before.
  140.                 If System.IO.File.Exists(dlgSaveFile.FileName) = True Then System.IO.File.Delete(dlgSaveFile.FileName)
  141.                 '// Create the SQLite database
  142.                 SQLiteConnection.CreateFile(dlgSaveFile.FileName)
  143.                 Dim sQuery As String = String.Empty
  144.                 For i = 0 To dgvInfo.RowCount - 1
  145.                     sQuery = sQuery & dgvInfo.Rows(i).Cells(0).Value.ToString & " " & dgvInfo.Rows(i).Cells(1).Value.ToString & ","
  146.                 Next
  147.                 '// Cut the last comma.
  148.                 If Microsoft.VisualBasic.Right(sQuery, 1) = "," Then sQuery = Mid(sQuery, 1, Len(sQuery) - 1)
  149.                 Dim CreateTable As String = String.Empty
  150.                 '/ Create table sql statement
  151.                 '/ CREATE TABLE IF NOT EXISTS SampleTable (AAA INTEGER,BBB TEXT,CCC REAL)
  152.                 CreateTable &= "CREATE TABLE IF NOT EXISTS " & Trim(txtTableName.Text) & " ("
  153.                 CreateTable &= sQuery & ")"
  154.                 '// Check File Exist
  155.                 If System.IO.File.Exists(dlgSaveFile.FileName) = True Then
  156.                     System.IO.File.Delete(dlgSaveFile.FileName)
  157.                 End If
  158.                 '// Create the SQLite database
  159.                 SQLiteConnection.CreateFile(dlgSaveFile.FileName)
  160.                 Using MyConn As New SQLiteConnection("Data Source=" & dlgSaveFile.FileName & ";Version=3;New=True;")
  161.                     MyConn.Open()
  162.                     Using MyCmd As New SQLiteCommand(CreateTable, MyConn)
  163.                         MyCmd.ExecuteNonQuery()
  164.                     End Using
  165.                 End Using
  166.                 '// START
  167.                 Try
  168.                     '/ Declare
  169.                     Dim DA As SQLiteDataAdapter
  170.                     Dim DS As DataSet
  171.                     '// Open connection
  172.                     Dim strConn As String = "Data Source=" & dlgSaveFile.FileName & ";Version=3;New=True;"
  173.                     Conn = New SQLiteConnection(strConn)
  174.                     Conn.Open()
  175.                     DA = New SQLiteDataAdapter("SELECT * FROM " & Trim(txtTableName.Text), Conn)
  176.                     DS = New DataSet
  177.                     DA.Fill(DS, "MyTest")
  178.                     dgvData.DataSource = DS.Tables("MyTest").DefaultView
  179.                     DS.Dispose()
  180.                     DA.Dispose()
  181.                     '/ dgvData for input value.
  182.                     Call InitializeGridData()
  183.                 Catch ex As Exception
  184.                     MessageBox.Show(ex.Message)
  185.                 End Try
  186.                 Conn.Close()
  187.                 MessageBox.Show("Created successfully.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  188.             Catch ex As Exception
  189.                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  190.             End Try
  191.         End If
  192.     End Sub

  193.     ' / --------------------------------------------------------------------
  194.     Private Sub InitializeGridData()
  195.         With dgvData
  196.             .RowHeadersVisible = True
  197.             .AllowUserToAddRows = True
  198.             .AllowUserToDeleteRows = True
  199.             .AllowUserToResizeRows = False
  200.             .MultiSelect = False
  201.             '// Need to modify each cell.
  202.             .SelectionMode = DataGridViewSelectionMode.CellSelect
  203.             .ReadOnly = False
  204.             '//
  205.             .Font = New Font("Tahoma", 9)
  206.             ' Automatically set the width.
  207.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  208.             '/ Adjust Header Styles
  209.             With .ColumnHeadersDefaultCellStyle
  210.                 .BackColor = Color.Navy
  211.                 .ForeColor = Color.White
  212.                 .Font = New Font("Tahoma", 9, FontStyle.Bold)
  213.             End With
  214.         End With
  215.     End Sub

  216.     ' / Get my project path
  217.     ' / AppPath = C:\My Project\bin\debug
  218.     ' / Replace "\bin\debug" with ""
  219.     ' / Return : C:\My Project\
  220.     Function MyPath(ByVal AppPath As String) As String
  221.         '/ MessageBox.Show(AppPath);
  222.         AppPath = AppPath.ToLower()
  223.         '/ Return Value
  224.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  225.         '// If not found folder then put the \ (BackSlash ASCII Code = 92) at the end.
  226.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  227.     End Function

  228.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  229.         Me.Close()
  230.     End Sub

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

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

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

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

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

0

กระทู้

33

โพสต์

372

เครดิต

Full Member

Rank: 3Rank: 3

เครดิต
372
โพสต์ 2019-10-2 22:12:17 | ดูโพสต์ทั้งหมด

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

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

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

GMT+7, 2024-4-19 21:30 , Processed in 0.276621 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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