Programming/MSSQL

C# MSSQL 연동하기

홍상길 2010. 2. 9. 10:33


using System.Data;
using System.Data.SqlClient;

1.  select

--------------------------------------------
  // DB 연결하기

            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

----------------------------------------------------
  // DB 연결
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Server=localhost;database=tempdb;uid=sa;pwd=";
  
  // 삽입 SQL 문
            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();