Development Environment: Windows 7, Visual Studio 2008,. Net 3.5, MySQL 5.1
Problem Found: An error occurred while inserting BLOB fields into the database table.
C #. Net 3.5 developed the winform program. The backend uses the MySQL 5.1.x database.
From the MySQL official website under the mysql-connector-net-6.5.4, installed in.. net. mysqlconnection and mysqlcommand are used to operate the database. CS, which contains a method for executing mysqlcommand to update data
private const string connectString = "server=127.0.0.1;uid=root;pwd=root;database=dbname";public static bool MysqlExcute(MySqlCommand cmd){ MySqlConnection conn = new MySqlConnection(connectString); conn.Open(); cmd.Connection = conn; int rtn = cmd.ExecuteNonQuery(); conn.Close(); return rtn > 0;}
The PIC table of the database has a longblob field pic_data, which stores image data.
Now the path of the image is obtained in the program. After the following program is executed, an error will be reported in the executenonquery statement in the mysqlexcute method.
The "system. byte []" object cannot be forcibly converted to the type "system. iconvertible". The following is the problem code.
// Read the image content filestream FS = new filestream (path, filemode. open, fileaccess. read); byte [] imgbyte = new byte [FS. length]; FS. read (imgbyte, 0, imgbyte. length); // Insert the image mysqlcommand cmd = new mysqlcommand ("insert into PIC (pic_data, upload_username, upload_datetime)" + "values (? Pic_name ,? Pic_data ,? Upload_username ,? Upload_datetime) "); cmd. Parameters. Add ("? Pic_name ", pic_name); cmd. Parameters. Add ("? Pic_data ", mysqldbtype. varbinary). value = imgbyte; cmd. Parameters. Add ("? Upload_username ", session. username); cmd. Parameters. Add ("? Upload_datetime ", datetime. Now. tostring (); If (mysqlhelper. mysqlexcute (CMD) {// uploaded successfully //...} else {//...}
The error occurs in
cmd.Parameters.Add("?pic_data", MySqlDbType.VarBinary).Value = imgByte;
This statement is not called
public MySqlParameter Add(string parameterName, MySqlDbType dbType);
But called
public MySqlParameter Add(string parameterName, object value);
Therefore, mysqldbtype. varbinary is treated "? The pic_data value is passed to cmd. parameters,
. Value = imgbyte and then "? The value of pic_data overwrites the value of imgbtye.
Directly execute cmd. executenonquery () because it is not specified? Pic_data Type Error
The correct method is
MySqlParameter param = new MySqlParameter();param.MySqlDbType = MySqlDbType.VarBinary;param.ParameterName = "?pic_data";param.Value = imgByte;cmd.Parameters.Add(param);
You can view the discussion information in the post.
Http://topic.csdn.net/u/20120603/01/1b6e0b18-0d94-4b3a-9116-b900bbedf652.html? Seed = 1712075088 & R = 78751636 # r_78751636
Thank you very much.
Answers and help provided by avphoenixi