2013-11-09 37 views
0

我一直在使用MySQL一段時間,但直到最近我才達到上傳文件的需要。 這裏是場景:我有一個C#控制檯應用程序與.NET連接器一起運行,我需要它允許用戶上傳PDF文件,並用外鍵將它插入到特定的表中。錯誤:在MySQL中插入BLOB導致null使用C#

因此,定義命令的連接後,它涉及到這樣的事情:

command.CommandText = "INSERT INTO targetTable (ForeignKey,file) VALUES (@key, @arq);"; 
    MySqlParameter FKParam = new MySqlParameter("@key", MySqlDbType.Int32,3); 
    FKParam.Value = _value; //Received as a function parameter 
    MySqlParameter fileParam new MySqlParameter("@arq", MySqlDbType.Blob,bytes.length); 
    FKParam.Value = bytes; //is the name of the variable which holds the readed bytes from a file. 
    command.Parameters.Add(FKParam); 
    command.Parameters.Add(fileParam); 
    command.ExecuteNonQuery(); 

這段代碼完美的作品...除了它沒有。我的意思是,新行創建的,除了文件列爲空。

這裏的表結構:

mysql> show columns from targetTable ; 
    +---------------------+--------------+------+-----+-------------------+-----------------------------+ 
    | Field    | Type   | Null | Key | Default   | Extra      | 
    +---------------------+--------------+------+-----+-------------------+-----------------------------+ 
    | targetTableID  | int(3)  | NO | PRI | NULL    | auto_increment    | 
    | ForeignKey   | int(3)  | YES |  | NULL    |        | 
    | file    | mediumblob | YES |  | NULL    |        |     
    +---------------------+--------------+------+-----+-------------------+-----------------------------+ 
    3 rows in set (0.00 sec) 

回答

0

OK,對不起,自應答。 這只是我花了將近兩天的坐鴨試圖找到這個解決方案。 因此,在使用各種其他工具檢查上傳僅包含PHPadmin和SQL Workbench的105KiB文件的過程之後,我(終於!!)意識到我可能會錯過某些東西(好吧,嗯!)。

不是在連接字符串中,而不是在數據類型或我插入參數的方式(有帖子關於一個將在ParameterCollecion添加Parameter的方式,以及他們在Add(new Parameter)AddWithValue(paramName,value)衝突。這兩部作品),以及絕對是不是 max_allowed_pa​​cket設置。再一次,它在105 KiB文件中「崩潰」!

所以......我做了一個SELECT * FROM targetTable,注意到不是只有文件列是空的...... FK列也是空的!

mysql> SELECT * FROM targetTable; 
    +---------------+------------+-----+ 
    | targetTableID | ForeignKey | arq | 
    +---------------+------------+-----+ 
    |    1 | NULL | NULL| 
    +---------------+------------+-----+ 
    1 row in set (0.00 sec) 

到那時,我意識到,參數設置與@角色,在Microsoft SQL Server變量如此普遍。到那時,只有到那時,我才意識到,這個字符並不是MySQL中使用更明智思想的人物,因爲它傾向於指向全局/私有變量。

解決方案?在

MySqlParameter FKParam = new MySqlParameter("@key", MySqlDbType.Int32,3); 
    FKParam.Value = _value; //Received as a function parameter 
    MySqlParameter fileParam new MySqlParameter("@arq", MySqlDbType.Blob,bytes.length); 

更換@key@arq?key?arq,而且要快樂!