简体   繁体   English

使用C#模拟mysql压缩功能

[英]Simulate mysql compress function using c#

I'd like to insert some byte data into a mysql blob column. 我想在mysql blob列中插入一些字节数据。 The data is large so I want to store it in a compressed way. 数据很大,所以我想以压缩方式存储它。

I'm using Entity Framework 3.5SP1 to insert the data into the mysql database using the latest mysql .net connector. 我正在使用Entity Framework 3.5SP1使用最新的mysql .net连接器将数据插入mysql数据库。 Is there a way to either use the entitiy framework to insert a blob into the mysql database (like insert into testtable (blobcolumn) values (compress('aaa')) ) or to emulate the compress function of mysql in c# and then insert the result in the database? 有没有一种方法可以使用entitiy框架将blob插入到mysql数据库中(例如, insert into testtable (blobcolumn) values (compress('aaa')) )或在c#中模拟mysql的compress功能,然后插入结果在数据库中?

Thanks 谢谢

Please find below my implementation using Ionic zip . 请在下面找到我使用Ionic zip的实现。 Hope that helps! 希望有帮助!

using System; using System.IO; using Ionic.Zlib; using System.Text; namespace Qobuz { public static class MySqlCompressHelper { public static byte[] MySqlCompress(this string str, CompressionLevel level = CompressionLevel.BestCompression) { return UTF8Encoding.UTF8.GetBytes(str).MySqlCompress(level); } public static byte[] MySqlCompress(this byte[] buffer, CompressionLevel level = CompressionLevel.BestCompression) { using (var output = new MemoryStream()) { output.Write(BitConverter.GetBytes((int)buffer.Length), 0, 4); using (var compressor = new ZlibStream(output, CompressionMode.Compress, level)) { compressor.Write(buffer, 0, buffer.Length); } return output.ToArray(); } } public static string MySqlUncompressString(this byte[] buffer) { return UTF8Encoding.UTF8.GetString(buffer.MySqlUncompressBuffer()); } public static byte[] MySqlUncompressBuffer(this byte[] buffer) { using (var output = new MemoryStream()) { using (var decompressor = new ZlibStream(output, CompressionMode.Decompress)) { decompressor.Write(buffer, 4, buffer.Length - 4); } return output.ToArray(); } } } }

在连接字符串中指定“ UseCompression”选项以启用数据包压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM