728x90
반응형
C#에서 VS2019 로 접속하는 예제에 대한 설명입니다.
접속 예제
using System.Data.SqlClient;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SqlConnection connection;
string connectString = string.Format(" Data Source={0},{1};" +
"Persist Security Info=false;Integrated Security=false;" +
"User ID={2};Password={3};",
ip, port, userid, passwd);
try
{
connection = new SqlConnection(connectString);
connection.Open();
bsysdbconn = true;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT @@VERSION ";
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
MessageBox.Show(rdr.GetString(0), "Inform", MessageBoxButtons.OK, MessageBoxIcon.Information);
rdr.close();
connection.Close();
}
catch (SqlException se)
{
MessageBox.Show(se.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
예제 설명
접속에 필요한 using
- using System.Data.SqlClient;
접속 선언 문
- SqlConnection connection;
접속 함수
- connection = new SqlConnection(connectString);
접속 String 설명
- Data Source={0},{1}; Persist Security Info=false;Integrated Security=false;User ID={2};Password={3};
- Integrated Security 는 윈도우 인증 할경우 사용하는 옵션으로 필요시 SSPI 를 넣어서 사용합니다.
- Persist Security Info의 기본값은 false이며, 모든 연결 문자열에서 이 기본값을 사용하는 것이 좋습니다.
- Persist Security Info를 true 로 설정하면 연결이 열린 다음 사용자 ID 및 암호와 같은 보안 관련 정보를 얻을 수 있기에 false 로 설정하면 연결을 열기 위해 보안 정보를 사용한 다음 삭제하므로 보안 관련 정보에 액세스할 수 없습니다.
접속 연결
- connection.Open();
Select 함수 선언
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = connection;
- connection을 sqlcommand와 연결
- cmd.CommandText = "SELECT @@VERSION ";
- 실행할 sql 문 Text에 입력
- SqlDataReader rdr = cmd.ExecuteReader();
- cmd를 실행하여 결과 data를 rdr 에 저장.
- rdr.Read();
- rdr 의 Data 를 읽음.
- rdr.GetString(0)
- 첫번째 Data를 String 으로 변환.
접속 관련 close 수행.
프로그램이 종료 될 경우 자동으로 close 되지만 코드에 따라서 종료 시킬 필요가 있으니 사용 후 close()는 해야한다.
- rdr.Read();
- cmd.Dispose();
- connection.Close();
728x90
반응형
'언어 > C' 카테고리의 다른 글
비주얼 스튜디오 2019 설치 (0) | 2021.11.11 |
---|
댓글