2011-11-10 4 views
0

datetime이라는 sql_DateTime 열이있는 SQL Server 테이블이 있습니다. 또한이 테이블의 단일 레코드에 매핑되는 C# 구조가 있습니다. 이 구조에서 DateTime 유형의 m_DateTime이라는 구성원이 있습니다. 나는,이 테이블에서 레코드를 검색 DataSet을 사용하고 내 m_DateTime 변수에 Dataset에서 sql_DateTime를 얻을려고 후C# 및 datasets를 사용하여 SQL Server에 DateTime을 읽거나 쓰는 방법

내 문제가 발생합니다. 다른 데이터 유형을 처리하는 방식과 비슷하게하려고하면 InvalidCastException이 표시됩니다.

그런 다음 내 GUI에서 DateTimePicker을 사용하여 날짜와 시간을 표시하고 설정할 수 있습니다.

참조 용으로 내 코드가 첨부되어 있습니다. 어떤 지침을 주셔서 감사합니다.

public bool GetExperiment(ref Experiment exp, int ExperimentID, ref string statusMsg) 
    { 
     bool ret = true; 
     statusMsg = "GetExperiment: "; 

     try 
     { 
      // Open the connection 
      conn.Open(); 

      // init SqlDataAdapter with select command and connection 
      string SelectString = 
       @"SELECT * " + 
       "FROM Experiment " + 
       "WHERE ExperimentID = " + ExperimentID.ToString(); 

      SqlDataAdapter daExperiments = new SqlDataAdapter(SelectString, conn); 

      // fill the dataset 
      DataSet dsExperiments = new DataSet(); 
      daExperiments.Fill(dsExperiments, "Experiment"); 

      // assign dataset values to proj object that was passed in 
      exp.m_ExperimentID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ExperimentID"]; 
      exp.m_ProjectID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ProjectID"]; 
      exp.m_Name = (string)dsExperiments.Tables["Experiment"].Rows[0]["Name"]; 
      exp.m_Description = (string)dsExperiments.Tables["Experiment"].Rows[0]["Description"]; 
      exp.m_UserID = (int)dsExperiments.Tables["Experiment"].Rows[0]["UserID"]; 

      // PROBLEM OCCURS HERE 
      exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"].Rows[0]["DateTime"]; 

     } 
     catch (Exception ex) 
     { 

      ret = false; 
      statusMsg += "Failed - " + ex.Message; 
     } 
     finally 
     { 

      // Close the connection 
      if (conn != null) 
      { 
       conn.Close(); 
      } 
     } 
     return ret; 
    } 


public class Experiment 
{ 
    public int m_ExperimentID; 
    public int m_ProjectID; 
    public string m_Name; 
    public string m_Description; 
    public int m_UserID; 
    public DateTime m_DateTime; 
} 
+0

MSSQL DATETIME을 DateTime .NET 구조로 변환하는 방법에는 온라인으로 수많은 기사가 있습니다. 내 생각에 잘못된 변수 유형을 사용하고 그 이유 때문에 캐스팅 될 수 없습니다. 읽기 : http://stackoverflow.com/questions/1181662/is-there-any-difference-between-datetime-in-c-sharp-and-datetime-in-sql-server –

답변

0

당신 말 :

exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"] 
             .Rows[0]["DateTime"]; 

주 이름을 :

나는 당신이 사용할 아직 sql_DateTime

그리고라는 이름의 열이 SQL 서버의 테이블을 가지고 . 그래도 캐스팅 문제가 발생한다는 것에 놀랐습니다. 실제로 이름이 맞지만 행에 값이 없으므로 DBNull.ValueDateTime 번으로 캐스팅하려고 할 가능성이 있습니까? 또한

, 내가 말하고 싶지만 :

  • 참조 exp을 통과 할 필요가 없습니다
  • 나는 것 개인적으로 별도의 데이터베이스 액세스에서 예외 처리; 난 당신이 데이터 바인딩을 사용하고있는 UI가 나는 SQL
+0

존 - 당신이 옳았다 고 생각합니다. . 내 sql 테이블의 datetime 열은 NULL을 허용하도록 설정되었으며,이 경우 값은 NULL입니다. 간단히 NULLS를 허용하지 않도록 변경하고 기존 레코드에 값을 입력하면 캐스팅 문제가 해결되었습니다. 어리석은 실수라고 생각했습니다. 왜 내가 참조를 통해 exp를 전달할 필요가 없다고 말한 것이 궁금하다. exp 객체를 호출 코드로 리턴해야한다. 어쩌면 내가 뭔가 놓친 것 같아. 어쨌든, 훌륭한 의견을 주셔서 감사합니다. –

+0

@BryanGreenway : http://pobox.com/~skeet/csharp/parameters.html –

+0

훌륭한 기사를 읽어보세요. 나를 위해 물건을 지 웁니다. 도움에 다시 한번 감사드립니다. –

0

에 직접 실험 ID 등의 명명 된 매개 변수를 대신 사용하십시오

  • 예외를 처리 할 것? 그렇다면, 적절한 속성에 구속하고 있습니까? 그리고 SQL 하나 nullable 유형 또는 아닌가요?

  • 0

    이 시도 :

     exp.m_DateTime = DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString()); 
    
    0

    문제는 데이터 (Tables["Experiment"])를 포함하는 DataTable의 컬럼 ["DateTime"] 유형 날짜 시간이 아니라 문자열입니다 생각하지 않습니다 수 있습니다.

    난 당신이 대안으로 생각 :

    당신이 항상 날짜 시간 확신이 있다면
    1. 는, 단순히 그것을 구문 분석 : 당신이 그것을 읽을하기 전에

      exp.m_DateTime =DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString()); 
      
    2. dsExperiments.Tables["Experiment"].Columns["DateTime"].DataType=typeof(DateTime);을 설정합니다.

    관련 문제