如何使用c#和数据集将DateTime读/写到SQL Server

本文关键字:写到 SQL Server DateTime 何使用 数据集 | 更新日期: 2023-09-27 18:14:10

我在SQL Server中有一个表,它有一个名为sql_DateTime、类型为datetime的列。我还有一个C#结构,它映射到这个表中的单个记录;在该结构中是CCD_ 4类型的名为CCD_。

当我使用DataSet从该表中检索一条记录,然后尝试将Dataset中的sql_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;
}

如何使用c#和数据集将DateTime读/写到SQL Server

你说:

我在SQL Server中有一个表,它有一个名为SQL_DateTime 的列

然而你使用:

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

记下名称。我很惊讶你的选角有问题。在现实中,是否可能您的名称正确,但您的行不包含值,所以您正试图将DBNull.Value强制转换为DateTime

此外,我想说:

  • 不需要通过引用传递exp
  • 我个人会将异常处理与数据库访问分开;我会让UI处理异常
  • 我会使用一个命名参数,而不是将实验ID直接包含在SQL中

是否使用数据绑定?如果是,您是否绑定到正确的属性?SQL类型是否可以为null?

试试这个:

        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);之前设置它。