C# with SQLite - 데이터베이스 연동 1
C# 2022. 2. 18. 14:29 |반응형
C#에 SQLite 데이터베이스를 연동해 보자.
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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
// 데이터베이스 생성 및 열기. 생성하려는 데이터베이스가 존재하면 열기만 한다.
SQLiteConnection connection = new SQLiteConnection("Data Source=" + Environment.CurrentDirectory + "/test.db");
connection.Open();
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = "CREATE TABLE IF NOT EXISTS test (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"birthday TEXT NOT NULL)";
// Execute the command and return the number of rows inserted/updated affected by it.
command.ExecuteNonQuery();
// 이미 존재하는 데이터는 'OR IGNORE'에 의해 무시된다.
command.CommandText = "INSERT OR IGNORE INTO test (id, name, birthday) VALUES (1, 'sean', '2020-01-20'), " +
"(2, 'david', '2021-11-03'), " +
"(3, 'john', '2022-05-17')";
int rowCount = command.ExecuteNonQuery();
Console.WriteLine("The number of rows inserted/updated affected by it: " + rowCount + "\n");
command.CommandText = "SELECT * FROM test";
SQLiteDataReader reader = command.ExecuteReader();
// Reads the next row from the resultset. True if a new row was successfully loaded and is ready for processing
while (reader.Read())
{
Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}, Birthday: {reader.GetString(2)}");
}
// 다음 SQLiteCommand 사용을 위해 SQLiteDataReader 사용이 끝나면 종료해야 한다.
reader.Close();
// The date() function returns the date in this format: YYYY-MM-DD.
// The julianday() function returns the Julian day - the number of days since noon in Greenwich
// on November 24, 4714 B.C. (Proleptic Gregorian calendar).
command.CommandText = "SELECT JULIANDAY(DATE('NOW')) - JULIANDAY(DATE(birthday)) FROM test WHERE id=2";
int days = Convert.ToInt32(command.ExecuteScalar());
Console.WriteLine("David's birthday was " + days + " days ago.");
connection.Close();
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
}
|
소스를 입력하고 빌드한다.
※ 참고
SQLite Download Page for Documentaion and Commend-Line Tools.
반응형
'C#' 카테고리의 다른 글
C# with SQLite - 데이터베이스 연동 3 (0) | 2022.02.19 |
---|---|
C# with SQLite - 데이터베이스 연동 2 (0) | 2022.02.18 |
C# Google Cloud Vision API - 구글 클라우드 비전 API 3 (0) | 2022.02.11 |
C# Google Cloud Vision API - 구글 클라우드 비전 API 2 (0) | 2022.02.11 |
C# Google Cloud Vision API - 구글 클라우드 비전 API 1 (0) | 2022.02.11 |