[c#] C# 직렬화를 이용한 데이터베이스 저장
C#에서 데이터를 데이터베이스에 저장하고 검색하기 위해서 직렬화를 이용하는 방법에 대해 알아보겠습니다. 직렬화는 데이터를 바이트 스트림 또는 다른 형식으로 변환하는 것을 의미합니다.
1. 데이터 직렬화
C#에서 객체를 직렬화하기 위해서는 System.Runtime.Serialization
네임스페이스를 사용합니다. 아래는 간단한 클래스를 직렬화 하는 예제 코드입니다.
using System;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, person);
}
}
2. 데이터베이스 저장
직렬화된 데이터를 데이터베이스에 저장하기 위해서는 바이트 배열로 변환한 후 데이터베이스에 저장합니다. 아래는 SQLite 데이터베이스를 사용하는 예제 코드입니다.
using System.Data.SQLite;
// ...
static void SaveToDatabase(byte[] data)
{
string connectionString = "Data Source=MyDatabase.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (var command = new SQLiteCommand(connection))
{
command.CommandText = "INSERT INTO Persons (Data) VALUES (@data)";
command.Parameters.AddWithValue("@data", data);
command.ExecuteNonQuery();
}
}
}
3. 데이터 검색
직렬화된 데이터를 조회하기 위해서는 바이트 배열을 역직렬화하여 객체로 변환합니다. 아래는 데이터베이스에서 데이터를 가져와 역직렬화하는 예제 코드입니다.
static Person GetPersonFromDatabase(int id)
{
string connectionString = "Data Source=MyDatabase.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (var command = new SQLiteCommand(connection))
{
command.CommandText = "SELECT Data FROM Persons WHERE Id = @id";
command.Parameters.AddWithValue("@id", id);
byte[] data = (byte[])command.ExecuteScalar();
MemoryStream stream = new MemoryStream(data);
IFormatter formatter = new BinaryFormatter();
return (Person)formatter.Deserialize(stream);
}
}
}
이제 직렬화를 이용하여 C#에서 데이터를 데이터베이스에 저장하고 검색하는 방법에 대해 알아보았습니다.
참고 자료:
- Microsoft Docs. (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/)