IT/C#

[C#] C#과 MSSQL2005 연동하기 개돌 - 3편

데브렉스 2011. 1. 11. 07:46
반응형

c#으로 돌아와서

 

using System.Data;

using System.Data.SqlClient;

 

요게 필요하다!!

 

2개를 소개하겠다.

select, insert

 

1.  select

--------------------------------------------

            SqlConnection con = new SqlConnection();
                con.ConnectionString = "Server=localhost;database=tempdb;uid=sa;pwd=";

            // Server='IP주소 가능', database = '테이블만든데이터베이스'

            // mssql 설치시 입력한 id와 pass


            string strSql = "SELECT * From diary WHERE date=@date";

            // *은 전체를 의미, diary 테이블로 부터 select한다

            // where 은 데이터를 필터링 해준다.


            SqlCommand cmd = new SqlCommand(strSql, con);
            cmd.Parameters.AddWithValue("@date", date);
            con.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            if (rd.Read())
            {
                date = rd["content"].ToString();
            }
            else
            {
                date = "저장된 자료가 없습니다.";
            }
            rd.Close();
            con.Close();
            return date;

---------------------------------------------------

 

2. insert

----------------------------------------------------

            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Server=localhost;database=tempdb;uid=sa;pwd=";
            string strSql = "INSERT INTO diary(content, datetime) VALUES(@content, @dateTime)";
            SqlCommand cmd = new SqlCommand(strSql, con);
            cmd.Parameters.AddWithValue("@content", content);
            cmd.Parameters.AddWithValue("@dateTime", date);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

//위와 동일 자세한 내용은 SQL책 혹은 검색을 해주세요 ^~^

---------------------------------------------------

 

DB연동하기 참 쉽죠잉

저는 이것땜에 2틀동안 개고생했다는 ㅠㅠ 여러분 부자되세요~

반응형