반응형

새로운 프로젝트를 생성한 후 솔루션 탐색기에서 솔루션 이름을 선택하고 마우스 우클릭을 하여 나온 메뉴에서 솔루션용 NuGet 패키지 관리를 선택합니다. 


찾아보기를 선택한 후, 입력창에 Sqlite를 입력하면 나오는 목록 중에서 System.Data.SQLite.Core를 선택합니다. 오른쪽에 보이는 프로젝트를 선택한 후.. 아래쪽에 있는 설치버튼을 클릭합니다. 


확인 버튼을 클릭하면 Sqlite 엔진이 프로젝트에 추가됩니다.


폼의 UI를 아래처럼 디자인합니다.


솔루션 탐색기의 프로젝트 이름을 선택한 후 마우스 우클릭을 하여 나온 메뉴에서 추가 - 모듈을 선택합니다.  ModuleDBConnection.vb라는 이름을 적은 후 추가버튼을 클릭합니다.  그리고 아래 코드를 작성합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Imports System.Data.SQLite
 
Module ModuleDBConnection
    Public connection As SQLiteConnection
 
    '데이터베이스 파일에 연결하기 위한 함수
    Sub connect()
 
        '디비 파일이 존재하는 지 검사
        If My.Computer.FileSystem.FileExists("data.db3"Then
            '이미 생성되어 있는 경우
            ' MsgBox("File found.")
 
            '데이터베이스 파일을 연다.
            Try
                connection = New SQLiteConnection("Data Source=data.db3")
                If connection.State = ConnectionState.Closed Then
                    connection.Open()
                End If
            Catch ex As Exception
                MsgBox("데이터베이스 연결 실패")
            End Try
        Else
            '없는 경우 새로 파일을 생성하고
            '필요한 테이블을 생성한다. 
            ' MsgBox("File not found.")
 
            SQLiteConnection.CreateFile("data.db3")
            Using Query As New SQLiteCommand()
                connection = New SQLiteConnection("Data Source=data.db3")
                connection.Open()
                With Query
                    .Connection = connection
                    .CommandText = "CREATE TABLE users(id INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(50), address varchar(50))"
                End With
                Query.ExecuteNonQuery()
                connection.Close()
            End Using
 
            '데이터베이스 파일을 연다.
            Try
                connection = New SQLiteConnection("Data Source=data.db3")
                If connection.State = ConnectionState.Closed Then
                    connection.Open()
                End If
            Catch ex As Exception
                MsgBox("데이터베이스 연결 실패")
            End Try
 
        End If
 
    End Sub
 
 
    ' SQL문을 실행하기 위한 함수
    Public Sub RunSQL(ByVal sql As String)
        Try
            connect()
            Dim cmd As New SQLiteCommand
            cmd.Connection = connection
            cmd.CommandType = CommandType.Text
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
            cmd.Dispose()
            connection.Close()
 
            'MsgBox("처리했습니다.")
        Catch ex As Exception
            MsgBox("처리에 실패했습니다. " + sql)
        End Try
    End Sub
 
End Module
 
cs


디자인 페이지에서 Form을 선택한 상태에서 마우스 우클릭하여 나온 메뉴에서 속성을 선택합니다. 오른쪽에 뜨는 속성창 상단에 보이는 이벤트 버튼을 클릭합니다. 


동작 항목에서 Load를 선택하고 오른쪽에 있는 공란을 더블클릭합니다.  

그리고 다음 코드를 추가합니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Imports System.Data.SQLite
 
Public Class Form1
 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'DataGridView를 선택하면 전체 한줄이 선택되게 됩니다. 
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
 
        showData()
    End Sub
 
    Sub showData()
        connect() 'DB에 연결한 후
 
        '데이터를 읽어와서 DataGridView에 출력합니다. 
        Dim dataAdapter As New SQLiteDataAdapter("select * from users", connection)
        Dim datatable As New DataTable
        dataAdapter.Fill(datatable)
        DataGridView1.DataSource = datatable
        connection.Close()
        dataAdapter.Dispose()
    End Sub
 
End Class
cs


디자인 페이지에서 추가버튼을 더블클릭한 후 코드가 생성되면 다음 코드를 추가합니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    Private Sub add_Button_Click(sender As Object, e As EventArgs) Handles add_Button.Click
 
        '공백을 입력할 수 없도록 에러처리 
        If name_TextBox.Text = "" Or address_TextBox.Text = "" Then
            MsgBox("데이터를 입력하세요")
            Return
        End If
 
        Dim SQL As String = "INSERT INTO users( name, address ) VALUES('" & name_TextBox.Text & "','" & address_TextBox.Text & "')"
        RunSQL(SQL)
        showData()
 
        '데이터가 입력되었던 텍스트박스를 비웁니다.
        name_TextBox.Text = ""
        address_TextBox.Text = ""
 
    End Sub
cs


실행시켜 보면 데이터가 DataGridView에 입력되는 것을 확인 할 수 있습니다. SQLite 디비 파일에 저장시켰다가 불러오기 때문에 프로그램을 종료시켰다가 다시 실행시켜도 데이터값이 똑같이 보입니다. 


디자인 페이지에서 삭제 버튼을 더블클릭한 후 코드가 생성되면  다음 코드를 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   Private Sub delete_Button_Click(sender As Object, e As EventArgs) Handles delete_Button.Click
        '삭제할 수 없는 셀인 경우 에러처리
        If DataGridView1.SelectedRows(0).Cells(0).Value = Nothing Then
            Return
        End If
 
        Dim id As Integer = DataGridView1.SelectedRows(0).Cells(0).Value
 
        Dim msgResult As MsgBoxResult = MsgBox("id=" & id & "인 데이터를 삭제하시겠습니까?", MsgBoxStyle.YesNo)
 
        If msgResult = MsgBoxResult.Yes Then
 
            Dim SQL As String = "DELETE FROM users where id=" & id & ""
 
            RunSQL(SQL)
            showData()
 
            name_TextBox.Text = ""
            address_TextBox.Text = ""
 
        End If
    End Sub
cs


삭제할 행을 선택한 후, 삭제 버튼을 클릭하면 지울건지 메시지 창이 보입니다. 예를 선택하면 해당 행이 삭제됩니다. 


이제 입력된 내용을 수정하는 것을 추가합니다. 우선 이미 DataGirdView에 입력된 데이터를 선택시 해당 데이터들이 텍스트뷰에 입력되도록 해야 합니다. DataGrdiView를 선택하고 오른쪽 상단에 있는 속성을 선택합니다.  마우스 하위 항목에 있는 CellClick옆에 있는 공간을  더블클릭합니다.

다음 코드를 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If (e.RowIndex > -1And Not (DataGridView1.SelectedRows(0).Cells(0).Value = NothingThen
            'DataGridView1에서 선택된 행의 두번째 셀의 값을 name_TextBox의 내용으로 합니다.
            name_TextBox.Text = DataGridView1.SelectedRows(0).Cells(1).Value.ToString
 
            'DataGridView1에서 선택된 행의 세번째 셀의 값을 address_TextBox의 내용으로 합니다.
            address_TextBox.Text = DataGridView1.SelectedRows(0).Cells(2).Value.ToString
        Else
            name_TextBox.Text = ""
            address_TextBox.Text = ""
        End If
    End Sub
cs


이제 DataGridView에서 행을 선택하면 해당 값들이 택스트박스에 출력됩니다.  


텍스트박스에 있는 값을 수정 하고나서 디비로 값을 업데이트를 하기 위한 처리를 위해 디자인 페이지에서 업데이트 버튼을 더블클릭하고 다음 코드를 추가합니다.

1
2
3
4
5
6
7
8
9
10
    Private Sub update_Button_Click(sender As Object, e As EventArgs) Handles update_Button.Click
        Dim id As Integer = DataGridView1.SelectedRows(0).Cells(0).Value
        Dim SQL As String = "UPDATE users SET name='" & name_TextBox.Text & "',address='" & address_TextBox.Text & "' WHERE id=" & id & ""
 
        RunSQL(SQL)
        showData()
 
        name_TextBox.Text = ""
        address_TextBox.Text = ""
    End Sub
cs


이제 수정을 원하는 행을 선택하면 오른쪽 택스트박스에 해당값이 출력되며 수정 후  업데이트 버튼을 클릭하면 디비와 DataGidView에 반영이 됩니다. 


검색기능을 넣어보기 위해서 디자인 페이지에서 search_TextBox라는 Name으로 텍스트박스를 하나 추가하고 속성창에서 TextChanged 이벤트를 추가합니다. 

1
2
3
4
5
6
7
8
9
    Private Sub search_TextBox_TextChanged(sender As Object, e As EventArgs) Handles search_TextBox.TextChanged
        connect()
        Dim dataAdapter As New SQLiteDataAdapter("SELECT * FROM users WHERE name like '" & search_TextBox.Text & "%'", connection)
        Dim datatable As New DataTable
        dataAdapter.Fill(datatable)
        DataGridView1.DataSource = datatable
        connection.Close()
        dataAdapter.Dispose()
    End Sub
cs


검색창에 검색어를 입력하면 해당하는 이름만 출력되는 것을 볼 수 있습니다. 


전체 소스코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Imports System.Data.SQLite
 
Public Class Form1
 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'DataGridView를 선택하면 전체 한줄이 선택되게 됩니다. 
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
 
        showData()
    End Sub
 
    Sub showData()
        connect() 'DB에 연결한 후
 
        '데이터를 읽어와서 DataGridView에 출력합니다. 
        Dim dataAdapter As New SQLiteDataAdapter("select * from users", connection)
        Dim datatable As New DataTable
        dataAdapter.Fill(datatable)
        DataGridView1.DataSource = datatable
        connection.Close()
        dataAdapter.Dispose()
    End Sub
 
    Private Sub add_Button_Click(sender As Object, e As EventArgs) Handles add_Button.Click
 
        '공백을 입력할 수 없도록 에러처리 
        If name_TextBox.Text = "" Or address_TextBox.Text = "" Then
            MsgBox("데이터를 입력하세요")
            Return
        End If
 
        Dim SQL As String = "INSERT INTO users( name, address ) VALUES('" & name_TextBox.Text & "','" & address_TextBox.Text & "')"
        RunSQL(SQL)
        showData()
 
        '데이터가 입력되었던 텍스트박스를 비웁니다.
        name_TextBox.Text = ""
        address_TextBox.Text = ""
 
    End Sub
 
    Private Sub delete_Button_Click(sender As Object, e As EventArgs) Handles delete_Button.Click
        '삭제할 수 없는 셀인 경우 에러처리
        If DataGridView1.SelectedRows(0).Cells(0).Value = Nothing Then
            Return
        End If
 
        Dim id As Integer = DataGridView1.SelectedRows(0).Cells(0).Value
 
        Dim msgResult As MsgBoxResult = MsgBox("id=" & id & "인 데이터를 삭제하시겠습니까?", MsgBoxStyle.YesNo)
 
        If msgResult = MsgBoxResult.Yes Then
 
            Dim SQL As String = "DELETE FROM users where id=" & id & ""
 
            RunSQL(SQL)
            showData()
 
            name_TextBox.Text = ""
            address_TextBox.Text = ""
 
        End If
    End Sub
 
    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If (e.RowIndex > -1And Not (DataGridView1.SelectedRows(0).Cells(0).Value = NothingThen
            'DataGridView1에서 선택된 행의 두번째 셀의 값을 name_TextBox의 내용으로 합니다.
            name_TextBox.Text = DataGridView1.SelectedRows(0).Cells(1).Value.ToString
 
            'DataGridView1에서 선택된 행의 세번째 셀의 값을 address_TextBox의 내용으로 합니다.
            address_TextBox.Text = DataGridView1.SelectedRows(0).Cells(2).Value.ToString
        Else
            name_TextBox.Text = ""
            address_TextBox.Text = ""
        End If
    End Sub
 
    Private Sub update_Button_Click(sender As Object, e As EventArgs) Handles update_Button.Click
        Dim id As Integer = DataGridView1.SelectedRows(0).Cells(0).Value
        Dim SQL As String = "UPDATE users SET name='" & name_TextBox.Text & "',address='" & address_TextBox.Text & "' WHERE id=" & id & ""
 
        RunSQL(SQL)
        showData()
 
        name_TextBox.Text = ""
        address_TextBox.Text = ""
    End Sub
 
    Private Sub search_TextBox_TextChanged(sender As Object, e As EventArgs) Handles search_TextBox.TextChanged
        connect()
        Dim dataAdapter As New SQLiteDataAdapter("SELECT * FROM users WHERE name like '" & search_TextBox.Text & "%'", connection)
        Dim datatable As New DataTable
        dataAdapter.Fill(datatable)
        DataGridView1.DataSource = datatable
        connection.Close()
        dataAdapter.Dispose()
    End Sub
End Class
 
cs



전체 프로젝트 압축파일입니다.

SQLite_Example.z01


SQLite_Example.zip



반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts