2017-04-25 82 views
1

我想在varbinary(max)中插入空值,但它返回錯誤。無法在varbinary(max)中插入空值,但出現錯誤:不允許將數據類型nvarchar隱式轉換爲varbinary(max)

我想下面的代碼保存照片,當我附上照片它沒有任何問題保存。當沒有照片時會拋出錯誤。

允許從數據類型nvarchar到varbinary(max)的隱式轉換不是 。使用CONVERT函數來運行此查詢。

protected void Button3_Click(object sender, EventArgs e) 
{ 
    newphoto pat = new newphoto(); 
    pat.id = id.Text; 
    byte[] photo = null; 
    if (Attch.HasFile) 
    { 
     Stream fs2 = Attch.PostedFile.InputStream; 
     BinaryReader br2 = new BinaryReader(fs2); 
     pat.photo = br2.ReadBytes((Int32)fs2.Length); 
    } 
    else 
    { 
     pat.photo = null; 
    } 
    pat.Addfile() 
} 

public bool Addfile() 
{ 
    Parameters.Clear(); 
    Parameters.AddWithValue("@pat_id", id); 
    if (photo == null) 
    { 
     Parameters.Add("@photo", SqlDbType.VarBinary, -1); 
     Parameters["@photo"].Value = DBNull.Value; 
    } 
    else 
    { 
     Parameters.AddWithValue("@photo", photo); 
    } 
    return FetchNonQuery(@"insert into mr_Info (@pat_id ,@photo)" + 
       " Values (@pat_id ,@photo)"); 
} 

protected bool FetchNonQuery(string CmdQuery) 
{ 
    bool result = false; 
    using (SqlConnection myConnection = DBConnection) 
    { 
     SqlCommand myCommand = new SqlCommand(CmdQuery, myConnection); 
     myCommand.CommandType = CommandType.Text; 
     //Set Parameters  
     foreach (SqlParameter Parameter in _parameters) 
     { 
      myCommand.Parameters.AddWithValue(Parameter.ParameterName, Parameter.Value); 
     } 
     //Execute the command 
     myConnection.Open(); 
     if (myCommand.ExecuteNonQuery() > 0) 
     { 
      result = true; 
     } 
     myConnection.Close(); 
    } 
    return result; 
} 
+1

試圖更改添加行_myCommand.Parameters.Add(Parameter); _ – Steve

+0

中的命令的參數也是INSERT命令錯誤。您使用字段名稱和值的參數。您應該寫入_INSERT INTO(pat_id,photo)VALUES(@pat_id,@ photo)_ – Steve

+0

可能重複[參數varbinary數據類型中的空值](http://stackoverflow.com/questions/18170985/null-value-in -a-parameter-varbinary-datatype) –

回答

2

這是造成AddWithValue呼叫個微妙的問題。 (和not the only one)。
當AddWithValue能夠正確識別參數的類型時,您沒有問題,但是當您將參數值設置爲DBNull.Value時,該方法會嘗試將其轉換爲字符串,並且您會收到錯誤,因爲數據字段期望VARBINARY。
但是,當您構建參數列表時,您可以精確地指定期望的類型,因此您可以簡單地將該參數傳遞給Add方法,而不是使用AddWithValue構建另一個參數。

foreach (SqlParameter Parameter in _parameters) 
{ 
    myCommand.Parameters.Add(Parameter); 
} 

你甚至可以

myCommand.Parameters.AddRange(_parameters.ToArray()); 

而且消除環路,在我的其他評論指出,INSERT命令應該寫成

INSERT INTO (pat_id,photo) VALUES (@pat_id ,@photo) 
相關問題