출처 : http://darby.wo.tc/blog/entry/C-C%EC%97%90%EC%84%9C-MySQL-%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0
[C#] C#에서 MySQL 연동하기.
모처럼 시험이 끝나서 뭔가 좋은정보 남길거 없나 하다가 본 강좌를 쓰게되었습니다.
그럼 시작해볼까요?
필자는 VS2008(한글판)을 사용하기때문에 VS2008 기준으로 설명하겠습니다.
먼저 다음 링크에 접속한뒤 .Net Connector 를 다운로드 하여 설치합니다.
( http://dev.mysql.com/downloads/connector/net/5.2.html )
설치를 정상적으로 마쳤다면 [프로젝트(P)] - [참조추가(R)] 의 .NET 탭에서 MySQL.Data 를 추가합니다.
추가후 using 문으로 MySql.Data.MySqlClient 를 선언해줍니다.
위 과정이 끝났다면 이제 본격적으로 연동할일만 남았습니다.
전역변수 선언
//커넥션 스트링
private static string strCnn;
//생성할 커넥션을 담을 변수
private static MySqlConnection oCnn = null;
private static string strCnn;
//생성할 커넥션을 담을 변수
private static MySqlConnection oCnn = null;
접속부분
private static int InitMYSQL(string database, string userid, string password)
{
//커넥션 스트링 생성
strCnn =
string.Format("data source=localhost; database={0}; user id={1}; password={2}"
,database ,userid ,password);
try
{
//생성된 커넥션 스트링으로 커넥션 만들기
oCnn = new MySqlConnection(strCnn);
//접속 고고씽
oCnn.Open();
return 0;
}
catch (MySqlException _e)
{
//실패하면 1을 리턴해주자
System.Console.WriteLine(_e.Message);
return 1;
}
}
사용예) if(InitMYSQL("Database이름", "아이디", "비번") == 0) { 접속 성공 처리부분 }{
//커넥션 스트링 생성
strCnn =
string.Format("data source=localhost; database={0}; user id={1}; password={2}"
,database ,userid ,password);
try
{
//생성된 커넥션 스트링으로 커넥션 만들기
oCnn = new MySqlConnection(strCnn);
//접속 고고씽
oCnn.Open();
return 0;
}
catch (MySqlException _e)
{
//실패하면 1을 리턴해주자
System.Console.WriteLine(_e.Message);
return 1;
}
}
SQL 명령어 실행부분
( 밑에 함수에서는 character 라는 테이블에 max_hp 필드데이타를 모두 가져오는 예제입니다.
제가 만들던 프로그램이 게임 관련 프로그램이라 본의아니게 게임관련 테이블과 필드명이.. ㅋ )
private static String GetDBMYSQL()
{
//명령어
MySqlCommand oCmd = null;
//명령 실행후 들어온 정보를 담을곳
MySqlDataReader oReader = null;
String sRet = "";
try
{
//명령어 생성
oCmd = new MySqlCommand("select * from `character` order by `max_hp` desc;", oCnn);
//생성한 명령어를 ExecuteReader() 를 이용하여 실행뒤 oReader 에 저장.
oReader = oCmd.ExecuteReader();
//
while (oReader.Read())
{
/* oReader.GetString("필드명")
* 다음 지정한 필드명에 있는 값을 읽어온다.
*/
sRet += oReader.GetString("max_hp");
sRet += "\n";
}
oReader.Close();
oReader = null;
oCmd = null;
}
catch (MySqlException _e)
{
System.Console.WriteLine(_e.Message);
}
return (sRet);
}
{
//명령어
MySqlCommand oCmd = null;
//명령 실행후 들어온 정보를 담을곳
MySqlDataReader oReader = null;
String sRet = "";
try
{
//명령어 생성
oCmd = new MySqlCommand("select * from `character` order by `max_hp` desc;", oCnn);
//생성한 명령어를 ExecuteReader() 를 이용하여 실행뒤 oReader 에 저장.
oReader = oCmd.ExecuteReader();
//
while (oReader.Read())
{
/* oReader.GetString("필드명")
* 다음 지정한 필드명에 있는 값을 읽어온다.
*/
sRet += oReader.GetString("max_hp");
sRet += "\n";
}
oReader.Close();
oReader = null;
oCmd = null;
}
catch (MySqlException _e)
{
System.Console.WriteLine(_e.Message);
}
return (sRet);
}
초기화부분
private static void FinalMYSQL()
{
try
{
if (oCnn != null)
{
oCnn.Close();
oCnn = null;
}
}
catch (MySqlException _e)
{
System.Console.WriteLine (_e.Message);
}
}
{
try
{
if (oCnn != null)
{
oCnn.Close();
oCnn = null;
}
}
catch (MySqlException _e)
{
System.Console.WriteLine (_e.Message);
}
}
위와 같이 간단히 MySQL 연동부터 쿼리문으로 테이블에 값을 얻어오는 부분까지 함수로 작성해보았습니다.
아주 쉽군요 ㅋ