본문 바로가기

Computerscience/C#

DB 연동하기

           
            bool bcheckIsConnection = false;
            SqlConnection oCnn = new SqlConnection();
            try
            {
                oCnn.ConnectionString = "server=서버IP(예:58.227.21.50);database=DB이름;user=sa;pwd=1234;;
                oCnn.Open();
                bcheckIsConnection = true;
            }
            catch {
                MessageBox.Show("에러 메시지");

            }
            if (bcheckIsConnection)
            {
                SqlCommand oCmm = new SqlCommand();
                oCmm.CommandType = CommandType.Text;
                oCmm.Connection = oCnn;
                oCmm.CommandText = "쿼리문";

                SqlDataReader oReader = oCmm.ExecuteReader();
                oReader.Read();
                try
                {
                    /* 쿼리결과로 수행해야 할 작업 */
                   // ex) string name = oReader[0].Tostring();
                    oReader.Close();
                    oCnn.Close();
                }
                catch
                {
                    oReader.Close();
                    oCnn.Close();
                    MessageBox.Show("에러메시지");
                }
            }