簡體   English   中英

如何使用C#和數據集將DateTime讀取/寫入SQL Server

[英]How to use c# and datasets to read/write DateTime to SQL Server

我在SQL Server中有一個表,該表具有名為datetime名為sql_DateTime的列。 我也有一個C#結構,它映射到該表中的一條記錄。 在此結構中是名為DateTime m_DateTime的成員。

我使用DataSet從該表中檢索記錄,然后嘗試將sql_DateTimeDataset到我的m_DateTime變量中后,出現了我的m_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;
}

你說:

我在SQL Server中有一個表,該表具有名為sql_DateTime的列

但是您使用:

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

注意名稱。 我很驚訝您遇到鑄造問題。 實際上,您是否有正確的名稱,但是您的行中沒有值,因此您嘗試將DBNull.ValueDateTime

另外,我會說:

  • 無需通過引用傳遞exp
  • 我個人將異常處理與數據庫訪問分開; 我會讓用戶界面處理異常
  • 我會使用命名參數,而不是將實驗ID直接包含在SQL中

您正在使用數據綁定嗎? 如果是這樣,您是否綁定到適當的屬性? SQL是可為空的類型嗎?

嘗試這個 :

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

問題可能是包含數據( Tables["Experiment"] )的DataTable認為列["DateTime"]的類型不是DateTime,而是字符串。

我認為您必須選擇:

  1. 如果您確定它始終是一個DateTime,只需對其進行解析:

     exp.m_DateTime =DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString()); 
  2. 設置dsExperiments.Tables["Experiment"].Columns["DateTime"].DataType=typeof(DateTime); 在嘗試閱讀之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM