在MySQL數據庫中,有一種blob數據類型,用來存儲文件。C#編程語言操作MySQL數據庫需要使用MySQL官方組件MySQL.Data.dll。
Mysql.Data.dll(6.9.6)組件下載地址:http://download.csdn.net/detail/keypig_zz/9262767。
現在說一說如何實現blob類型數據的操作。
新建winform程序,添加兩個按鈕。代碼如下:
1 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 2 private void button1_Click(object sender, EventArgs e) 3 { 4 //測試序列化與反序列化 5 int[] arr = { 1, 2, 3 }; 6 BinaryFormatter bFormatter = new BinaryFormatter(); 7 bFormatter.Serialize(ms, arr); 8 byte[] byteArr = ms.ToArray(); 9 MessageBox.Show(byteArr.Length.ToString()); 10 MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.MySqlConnectString); 11 //string insertStr = "update mm set aa=4,arr=@blobData where aa=4;"; 12 string insertStr = "insert into mm(arr) values(@blobData);";//需要主鍵設置自增 13 MySqlParameter par=new MySqlParameter("@blobData",MySqlDbType.Blob); 14 par.Value=byteArr; 15 MySqlCommand cmd = new MySqlCommand(insertStr, conn); 16 cmd.Parameters.Add(par); 17 try 18 { 19 conn.Open(); 20 cmd.ExecuteNonQuery(); 21 ms.Close(); 22 ms.Dispose(); 23 } 24 catch (Exception ep) 25 { 26 MessageBox.Show(ep.Message); 27 } 28 29 30 } 31 32 private void button2_Click(object sender, EventArgs e) 33 { 34 BinaryFormatter bFormatter = new BinaryFormatter(); 35 36 MySql.Data.MySqlClient.MySqlDataReader myData; 37 MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(Properties.Settings.Default.MySqlConnectString); 38 string readStr = "select arr from mm where id =6;"; 39 MySqlCommand cmd = new MySqlCommand(readStr, conn); 40 try 41 { 42 conn.Open(); 43 myData = cmd.ExecuteReader(); 44 if (!myData.HasRows) 45 { 46 throw new Exception("沒有blob數據"); 47 } 48 myData.Read(); 49 byte[] blob = new byte[myData.GetBytes(0, 0, null, 0, int.MaxValue)]; 50 myData.GetBytes(0, 0, blob, 0, blob.Length); 51 myData.Close(); 52 ms = new System.IO.MemoryStream(blob); 53 ms.Position = 0; 54 int[] arr = (int[])bFormatter.Deserialize(ms); 55 ms.Dispose(); 56 string arrStr = null; 57 for (int i = 0; i < arr.GetLength(0); i++) 58 { 59 arrStr += arr[i].ToString()+" "; 60 } 61 MessageBox.Show(arrStr); 62 } 63 catch(Exception ep) 64 { 65 MessageBox.Show(ep.Message); 66 } 67 68 }
代碼中的連接字符串存儲於Settings中,具體格式為:“server=127.0.0.1;user=root;database=***;port=3306;password=***;”。數據庫中存在叫做mm的一個表格,含有一個id字段(主鍵,自增),一個arr字段(blob類型)。
上述代碼將一個整型數組{1,2,3}序列化之後以blob數據類型存儲在MySQL數據庫中,進一步,又從MySQL數據庫中讀取blob數據,進行反序列化,得到整型數組{1,2,3}。代碼執行結果如下: