2009-10-01 5 views
12

내 현재 프로젝트에서 단일 값 (id = val 인 테이블에서 열을 선택)을 얻으려면 이전 프로그래머가 datarow, datatable 및 sqldatadapter (물론 sqlconnection)를 사용하여 해당 값을 얻습니다.C#에서 간단한 SQL을 선택 하시겠습니까?

간단한 선택 쿼리를 만드는 더 쉬운 방법이 있습니까? PHP에서는, 난 mysql_query 다음 mysql_result을 사용할 수 있습니다.

내가 할 만 할 수 있다면 좋을 것이다 : 어떤 조언을위한

SqlConnection conSql = new SqlConnection(ConnStr); 
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql); 
conSql.Close(); 
return obj[0]; 

감사합니다.

+2

을 솔루션뿐만 아니라 팁도 제공합니다. LINQ를 살펴 보도록 권합니다. LINQ는 데이터베이스 쿼리뿐만 아니라 많이! –

+9

+1 : 질문 제목에서 이탤릭을 존경해야합니다. – Rik

+0

엔터프라이즈 라이브러리 데이터 블록을 권장합니다. 그것은 대부분의 db 호출의 간단한 작업을합니다. http://msdn.microsoft.com/en-us/library/dd203099.aspx –

답변

35

DataReaderDataAdapter을 건너 뛰고 sql 명령에 ExecuteScalar()을 호출하면됩니다.

using (SqlConnection conn = new SqlConnection(connString)) 
{ 
     SqlCommand cmd = new SqlCommand("SELECT * FROM whatever 
             WHERE id = 5", conn); 
     try 
     { 
      conn.Open(); 
      newID = (int)cmd.ExecuteScalar(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
} 
+0

감사합니다. 아마도 지금이 솔루션을 사용할 것입니다. 고맙습니다! – Chris

+1

여기서 주목해야 할 점은'ExecuteScalar'는 결과의 첫 번째 열의 첫 번째 행을 반환한다는 것입니다. 필드 이름을 명시 적으로 사용하는 것이 좋습니다. 이처럼 뭔가가 더 나은'선택 가기 1 MyField ... 정렬 asc/desc' 필요한 단일 값을 얻을 수 있습니다. –

+0

이 네임 스페이스 추가'using System.Data.SqlClient; –

5

실제로, 단순히 반환 된 결과의 첫 번째 행에서의 첫 번째 필드를 반환하는 방법 SqlCommand.ExecuteScalar()이 존재한다. 너만을 위해서.

.NET Framework Class Library SqlCommand..::.ExecuteScalar Method

쿼리를 실행하고 쿼리에 의해 반환되는 결과 집합에서 첫 번째 행의 첫 번째 열을 반환한다. 추가 열 또는 행은 무시됩니다.

+0

+1 "Just for you" – Elliott

4
당신은 매우 비슷한 할 수

: 당신이뿐만 아니라 요구 되었기 때문에

당신은 아마 SqlCommand를 찾고 있습니다
using (SqlConnection conn = new SqlConnection(ConnStr)) 
using (SqlCommand cmd = new SqlCommand(sql_string, conn)) 
{ 
    conn.Open(); 
    return cmd.ExecuteScalar(); 
} 
8

SqlDataReader

Dictionary<int, string> users = new Dictionary<int, string>(); 
using(SqlConnection connection = new SqlConnection("Your connection string")) 
{ 
    string query = "SELECT UserId, UserName FROM Users"; 
    SqlCommand command = new SqlCommand(query, connection); 
    connection.Open(); 
    using (SqlDataReader reader = command.ExecuteReader()) 
    { 
     while (reader.Read()) 
      users.Add(reader.GetInt32(0), reader.GetString(1)); 
    } 
    connection.Close(); 
} 
+2

+1 독자 사용. 그러나 컬럼 인덱스를 사용해서는 안됩니다 !!! 또한 connection.Close가 필요하지 않습니다 ("using"문으로 처리됩니다). – Chris

관련 문제