ADO.NET 을 이용한 데이터베이스 쿼리문 날리기.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DB접속하기
{
    class Program
    {
        static void Main(string[] args)
        {

            //string conn = "server=192.168.0.125;database=class;uid=sa;pwd=rlaxogml";
            //SqlConnection sct = new SqlConnection(conn);
            SqlConnection sct = new SqlConnection();
            sct.ConnectionString = "server=192.168.0.125;database=class;uid=sa;pwd=rlaxogml";
            sct.Open();

            try
            {
                Console.WriteLine("접속 되었습니다.");
                Console.WriteLine(sct.ServerVersion.ToString());
                Console.WriteLine(sct.State.ToString());
                sct.Close();

                Console.WriteLine("다른 데이터 베이스로 접속합니다.");
                Console.WriteLine("아이디를 입력해주세요.");
                string a = Console.ReadLine();
                Console.WriteLine("비밀번호를 입력해주세요.");
                string b = Console.ReadLine();
                sct.ConnectionString = "server=localhost;database=MYDIARY;uid="+a+";pwd="+b;
                sct.Open();

                Console.WriteLine("로컬 호스트로 접속되었습니다.");
                Console.WriteLine(sct.State.ToString());

                Console.WriteLine("데이터베이스를 변경합니다.");
                sct.ChangeDatabase("TOTALRESULT");
                Console.WriteLine("데이터베이스가 변경되었습니다.");

                string sqlquery = "SELECT * FROM RESULT";
                SqlCommand scm = new SqlCommand(sqlquery, sct);
                SqlDataReader sdr = scm.ExecuteReader();
                Console.WriteLine(sct.ServerVersion.ToString());

                while (sdr.Read())
                {
                    //Console.WriteLine(sdr[0].ToString() + ":\n" + sdr[1].ToString() + ":" + sdr[2].ToString() + ":" + sdr[3].ToString());
                    for (int i = 0; i < sdr.FieldCount; i++)
                    {
                        Console.WriteLine(sdr[i].ToString()); 
                    }
                }
                Console.WriteLine(sct.State.ToString());
                sct.Close();
            }


            catch (Exception ex)
            {
                sct.Close();
                Console.WriteLine("접속이 실패하였습니다.");
            }

            finally
            {
                sct.Close();
                Console.WriteLine("접속을 강제로 종료합니다.");
                Console.WriteLine(sct.State.ToString());
            }
        }
    }
}




간단합니다. 주석처리 해둔 건 수업시간에 배웠던 거. 무시하셔도 됩니다.

by 李君 | 2009/06/17 15:46 | 즐거운 것 | 트랙백 | 덧글(0)

트랙백 주소 : http://haken.egloos.com/tb/4167777
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶