2015-07-20 93 views
2

我找不到为什么我的第二个参数(NotifyDateParameter)对于我的SqlCommand无法正常工作。它不会给出错误,但它在我的SQL Server数据库中显示为空。第一个参数(StringParameter)与预期一致。我现在可以利用你的一些专业知识。MVC:SqlCommand在数据库中显示为空的第二个参数

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); 
} 
+0

什么是NotifyDate对SQL表本身的数据类型? –

回答

0

那么对于初学者尝试做两件事情

  1. NotifyDateParameter.ParameterName = "@NotifyDate"; // @added to parameter name更换NotifyDateParameter.ParameterName = "NotifyDate";
  2. 检查参数类型是SqlDbType.DateTimeSqlDbType.Date
+0

将其更改为“@NotifyDate”工作!谢谢。我只是好奇,为什么我不需要在“ImageData”之前添加“@”字符才能工作?这个参数一直没有它... – Vigs

+0

@Vigs - 以前也发生过我。我无法找到背后的逻辑。 –

相关问题