MVC:SqlCommand的第二个参数在数据库中显示为Null

时间:2015-07-20 00:26:44

标签: c# sql-server asp.net-mvc datetime

我无法弄清楚为什么我的NotifyDateParameter的第二个参数(SqlCommand)无法正常工作。它不会出错,但在我的SQL Server数据库中显示为null。第一个参数(StringParameter)与预期一致。我现在可以使用你的一些专业知识。

try
{
    {
        string connstr = @"Server=.\SQLEXPRESS;Database=ImageDB;Trusted_Connection=True;";

        SqlConnection conn = new SqlConnection(connstr);
        conn.Open();

        string query;
        byte[] fileData = null;

        using (var binaryReader = new BinaryReader(Request.Files[upload].InputStream))
        {
            fileData = binaryReader.ReadBytes(Request.Files[upload].ContentLength);
        }

        query = "insert into Images(ImageData, NotifyDate) values(@ImageData, @NotifyDate)";

        SqlParameter StringParameter = new SqlParameter();
        StringParameter.SqlDbType = SqlDbType.VarBinary;
        StringParameter.ParameterName = "ImageData";
        StringParameter.Value = fileData;

        DateTime today = DateTime.Now;
        DateTime notifyDate = today.AddDays(1);
        //string notifyDateString = notifyDate.ToString();

        SqlParameter NotifyDateParameter = new SqlParameter();
        NotifyDateParameter.SqlDbType = SqlDbType.DateTime;
        NotifyDateParameter.ParameterName = "NotifyDate";
        NotifyDateParameter.Value = notifyDate;

        SqlCommand cmd = new SqlCommand(query, conn);

        cmd.Parameters.Add(StringParameter);
        cmd.Parameters.Add(NotifyDateParameter);

        cmd.ExecuteNonQuery();       

        cmd.Dispose();
        conn.Close();
        conn.Dispose();
    }
}
catch (Exception e)
{
    string exceptionCause = String.Format("An error occurred: '{0}'", e);
    System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
} 

1 个答案:

答案 0 :(得分:0)

首先尝试2件事

  1. NotifyDateParameter.ParameterName = "NotifyDate";替换为NotifyDateParameter.ParameterName = "@NotifyDate"; // @added to parameter name
  2. 检查参数类型是SqlDbType.DateTime还是SqlDbType.Date