C# MySQL Singleton DB Connection

소스

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
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace WebApplication.ClassFolder{

public class DBConfig{
private static string Server = "";
private static string Database = "";
private static string ID = "";
private static string PASS = "";

static string conf = "Server=" + Server + ";Database=" + Database + ";Uid=" + ID + ";Pwd=" + PASS;

static MySqlConnection db;

public static MySqlConnection Connection{
get{
if (db == null){
LazyInitializer.EnsureInitialized(ref db, CreateConnection);
}
return db;
}
}

static MySqlConnection CreateConnection(){
var db = new MySqlConnection(conf);

db.Open();
return db;
}

// 강제로 커넥션을 끊어야될 경우가 있을 때
static void CloseConnection(){
if(db != null) {
db.Close();
db.Dispose();
db = null;
}
}

}
}

예제

1
2
// get Connection
var db = DBConfig.Connection;