VB.NET을 사용하여 MariaDB 데이터베이스에 CRUD(생성, 읽기, 갱신, 삭제) 작업을 수행하는 방법을 단계별로 설명하겠습니다. 이를 위해 MariaDB 데이터베이스와의 연결을 설정하고, VB.NET에서 기본적인 SQL 명령을 실행하는 방법을 다룹니다.
준비 사항
MariaDB 설치: 로컬에 MariaDB 서버가 설치되어 있어야 합니다. MariaDB는 무료로 다운로드하여 설치할 수 있습니다.
MySQL Connector: .NET과 MariaDB를 연결하기 위해 MySQL Connector for .NET이 필요합니다. 이 라이브러리는 MariaDB 및 MySQL 데이터베이스 서버와 통신할 수 있게 해 줍니다. NuGet 패키지 관리자에서
MySql.Data
패키지를 설치할 수 있습니다.VB.NET 개발 환경: Visual Studio 등의 IDE가 필요합니다.
데이터베이스 및 테이블 설정
MariaDB에 간단한 테이블을 생성합니다. 이 예제에서는 customers
라는 테이블을 사용합니다.
CREATE DATABASE TestDB;
USE TestDB;
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
);
위 SQL 명령어를 사용하여 TestDB
데이터베이스와 customers
테이블을 생성합니다.
VB.NET에서 MariaDB 연결
Visual Studio에서 새 프로젝트 생성
- Visual Studio를 열고 새로운 VB.NET 콘솔 애플리케이션을 만듭니다.
- 프로젝트 이름을 설정하고 생성합니다.
NuGet 패키지 설치
Tools
>NuGet Package Manager
>Manage NuGet Packages for Solution
으로 이동하여MySql.Data
패키지를 검색하고 설치합니다.
코드 작성
다음은 VB.NET에서 MariaDB 데이터베이스와 연결하여 CRUD 작업을 수행하는 예제입니다.
VB.NET 코드 예제
Imports MySql.Data.MySqlClient
Module Module1
' MariaDB 연결 문자열 설정
Dim connectionString As String = "Server=localhost;Database=TestDB;User ID=root;Password=yourpassword;SslMode=none;"
Sub Main()
' Create
CreateCustomer("Alice", "alice@example.com", 30)
' Read
ReadCustomers()
' Update
UpdateCustomer(1, "Alice Johnson", "alice.johnson@example.com", 31)
' Delete
DeleteCustomer(1)
' Read again to see changes
ReadCustomers()
Console.ReadLine()
End Sub
Sub CreateCustomer(name As String, email As String, age As Integer)
Using connection As New MySqlConnection(connectionString)
Try
connection.Open()
Dim query As String = "INSERT INTO customers (name, email, age) VALUES (@name, @email, @age)"
Using command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("@name", name)
command.Parameters.AddWithValue("@email", email)
command.Parameters.AddWithValue("@age", age)
command.ExecuteNonQuery()
End Using
Console.WriteLine("Customer created successfully.")
Catch ex As Exception
Console.WriteLine("An error occurred: " & ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
Sub ReadCustomers()
Using connection As New MySqlConnection(connectionString)
Try
connection.Open()
Dim query As String = "SELECT * FROM customers"
Using command As New MySqlCommand(query, connection)
Using reader As MySqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine("ID: " & reader("id").ToString() & ", Name: " & reader("name").ToString() & ", Email: " & reader("email").ToString() & ", Age: " & reader("age").ToString())
End While
End Using
End Using
Catch ex As Exception
Console.WriteLine("An error occurred: " & ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
Sub UpdateCustomer(id As Integer, name As String, email As String, age As Integer)
Using connection As New MySqlConnection(connectionString)
Try
connection.Open()
Dim query As String = "UPDATE customers SET name=@name, email=@email, age=@age WHERE id=@id"
Using command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("@id", id)
command.Parameters.AddWithValue("@name", name)
command.Parameters.AddWithValue("@email", email)
command.Parameters.AddWithValue("@age", age)
command.ExecuteNonQuery()
End Using
Console.WriteLine("Customer updated successfully.")
Catch ex As Exception
Console.WriteLine("An error occurred: " & ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
Sub DeleteCustomer(id As Integer)
Using connection As New MySqlConnection(connectionString)
Try
connection.Open()
Dim query As String = "DELETE FROM customers WHERE id=@id"
Using command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("@id", id)
command.ExecuteNonQuery()
End Using
Console.WriteLine("Customer deleted successfully.")
Catch ex As Exception
Console.WriteLine("An error occurred: " & ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
End Module
코드 설명
연결 문자열(
connectionString
): 데이터베이스 서버의 위치, 데이터베이스 이름, 사용자 이름, 비밀번호 등의 정보를 포함하여 MariaDB 서버에 연결하는 데 사용됩니다.yourpassword
부분을 실제 MariaDB 비밀번호로 바꿔야 합니다.CreateCustomer: 주어진 이름, 이메일, 나이로 새로운 고객 레코드를
customers
테이블에 삽입합니다.ReadCustomers:
customers
테이블에서 모든 레코드를 읽고 각 고객의 정보를 출력합니다.UpdateCustomer: 지정된
id
를 가진 고객의 정보를 주어진 이름, 이메일, 나이로 업데이트합니다.DeleteCustomer: 지정된
id
를 가진 고객 레코드를 삭제합니다.Using 구문: 데이터베이스 연결과 명령을 관리합니다.
Using
블록을 사용하면 명시적으로 닫지 않아도 블록이 끝날 때 자동으로 리소스가 해제됩니다.
실행 방법
위 코드를
Visual Studio
에 붙여 넣고yourpassword
를 MariaDB의 실제 비밀번호로 변경합니다.F5
를 눌러 프로그램을 실행합니다.각 CRUD 작업이 수행되면서 콘솔에 출력이 나타납니다.
주의사항
데이터베이스 연결 보안: 프로덕션 환경에서는 연결 문자열에 보안을 강화해야 합니다. 예를 들어, 환경 변수나 보안 구성 파일에 암호화하여 저장합니다.
예외 처리: 코드에서 발생할 수 있는 예외를 처리하여 프로그램이 비정상적으로 종료되지 않도록 합니다.
이 예제는 VB.NET에서 MariaDB 데이터베이스에 CRUD 작업을 수행하는 기본적인 방법을 보여 줍니다. 실제 애플리케이션에서는 데이터베이스 연결을 보다 안전하고 효율적으로 관리하는 추가적인 고려가 필요합니다.
'Software > BASIC' 카테고리의 다른 글
VB.NET 시작하기 - PNG 이미지 생성 (0) | 2024.07.29 |
---|---|
VB.NET 시작하기 - 바코드 (0) | 2024.07.29 |
Visual Basic 소개 (0) | 2024.07.29 |
VB.NET 소개 (0) | 2024.07.29 |
BASIC 설명 (0) | 2024.07.29 |