2013-03-17 5 views
0

내가 GUI와 간단한 응용 프로그램을 만들려면 어디에서 할 수있는 문자열로 업데이트해야합니다 입력 SQL 서버 이름과 ID :C#의 SQL 연결

update docs SET locked=0 WHERE ID=(id entered in GUI) 

어떤 제안이?

+2

이미 코드를 추가하십시오! – KF2

답변

7

당신은 업데이트 수행 C#을 함수를 작성할 수 있습니다

public int Update(int id) 
{ 
    string connectionString = "... put the connection string to your db here ..."; 
    using (var conn = new SqlConnection(connectionString)) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = "UPDATE docs SET locked = 0 WHERE ID = @id"; 
     cmd.Parameters.AddWithValue("@id", id); 
     return cmd.ExecuteNonQuery(); 
    } 
} 

을 그리고 당신은 그것을 당신이 UI에서 얻은 몇 가지 동적 값을 전달하여이 함수를 호출 할 수 있습니다

int id; 
if (int.TryParse(someTextBox.Text, out id)) 
{ 
    int affectedRows = Update(id); 
    if (affectedRows == 0) 
    { 
     MessageBox.Show("No rows were updated because the database doesn't contain a matching record"); 
    } 
} 
else 
{ 
    MessageBox.Show("You have entered an invalid ID"); 
} 
0

을 .NET 프레임 워크는 SQL 연결에 ADO.Net을 사용합니다. ADO.Net에서 간단한 쿼리는 다음과 같이 실행할 수 있습니다 : 당신의 자신의 연결 문자열에

SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Yourdatabase;Integrated Security=SSPI"); 
int res = 0; 
try 
{ 
conn.Open(); 
SqlCommand cmd = new SqlCommand("update docs SET locked=0 WHERE ID= @id"); 
cmd.Parameters.AddWithValue("@id", txtid.text); 
res = cmd.ExecuteNonQuery(); 
}catch(Exception err){ 
MessageBox.Show(err.getMessage()); 
}finally{ 
conn.Close(); 
} 
  1. 변경 연결 문자열을.
  2. SQL Express를 사용하는 경우 localhost \ SQLEXPRESS (로컬)로 변경하십시오.
  3. "txtid.text"를 ID를 얻을 수있는 문으로 변경하십시오.
  4. res를 확인하여 영향을받은 행 수를 알아낼 수도 있습니다.