2012-10-20 2 views
1

MySQL 데이터베이스에 연결하기 위해 IP를 입력 할 수있는 Windows 응용 프로그램 양식이 있습니다. 필요한 도움말은 프로그래밍 방법입니다. 따라서 입력 IP가 없거나 응답하지 않으면 양식에서 메시지를 반환하고 기본 IP 즉 localhost에 연결해야합니다.두 개의 IP 주소 사이를 결정하십시오

답변

0

이 같은 것을 시도 할 수

public bool TryConnect(string ServerIP, out MySqlConnection connection) 
{ 
    try 
    { 
     const string connectionString = "Server={0};Database=<database>;Uid=<username>;Pwd=<password>;"; 
     var conn = new MySqlConnection(string.Format(connectionString, ServerIP)); 

     conn.Open(); 
     conn.Close(); 
     connection = conn; 
     return true; 
    } 
    catch (Exception) 
    { 
     connection = null; 
     return false; 
    } 
} 
+1

가 입력 주셔서 감사합니다! –

0

원격 데이터베이스에 처음 연결하면 어떤 이유로 든 실패 할 수 있습니다 (IP가 유효하지만 서버가 실행 중이고 도달 할 수없는 경우에도 실패 할 수 있음) 로컬 데이터베이스에 연결하십시오 사용자에게 알리십시오).

MySqlConnection connection; 

if (this.TryConnect("xxx.xxx.xxx.xxx", out connection)) 
{ 
    // display error message here 
} 
else if (this.TryConnect("localhost", out connection)) 
{ 
    // code here 
} 

을 여기처럼 TryConnect 기능이 보이는 내용은 다음과 같습니다 :