如何从MySQL表检索Blob数据并转换为JSON格式及正确性验证
问题分析与解决方案
核心问题:Blob数据读取错误
你当前用reader.GetString(1)读取Blob类型是错误的——Blob是二进制数据,直接转字符串会得到非预期结果(比如你看到的@MyBlob)。JSON无法直接存储二进制数据,标准做法是将二进制数据编码为Base64字符串,这样可以安全序列化为JSON。
其他代码问题及修正
你的代码还存在几个关键问题,修正后才能正确返回多记录的JSON:
1. 消除SQL注入风险
不要用string.Format拼接SQL语句,改用参数化查询:
string sqlSelect = "Select MyDate, MyBlob from MyTablee WHERE Id = @Id"; sqlcmd.Parameters.AddWithValue("@Id", Id);
2. 循环内创建新的实体对象
你当前在循环外只创建了一个MyData实例,每次循环仅修改它的属性,导致列表中所有元素都是同一个对象的引用,最终所有项都会是最后一条记录的数据。需要在while(reader.Read())内部创建新对象:
while (reader.Read()) { var data = new MyData(); // 每次循环创建新实例 // 赋值逻辑... MyList.Add(data); }
3. 正确读取Blob并转Base64
Blob是二进制数据,需用reader.GetBytes读取后转Base64:
// 读取Blob列 long blobLength = reader.GetBytes(1, 0, null, 0, 0); byte[] blobBytes = new byte[blobLength]; reader.GetBytes(1, 0, blobBytes, 0, (int)blobLength); data.MyBlob = Convert.ToBase64String(blobBytes);
4. 修正变量名与资源释放
代码最后序列化的results未定义,应改为MyList;同时要正确用using包裹MySqlConnection和MySqlCommand,确保资源自动释放。
5. 标准化日期格式
读取MyDate时,建议转成ISO8601标准格式字符串,避免本地化格式问题:
DateTime myDate = reader.GetDateTime(0); data.MyDate = myDate.ToString("o"); // 输出如2023-01-30T21:16:40.0000000
完整修正后的代码
public class MyData { public string? MyDate { get; set; } public string? MyBlob { get; set; } } public async Task<string> GetQueryResult(string Id) { List<MyData> myList = new List<MyData>(); string sqlSelect = "Select MyDate, MyBlob from MyTablee WHERE Id = @Id"; try { using (MySqlConnection connection = new MySqlConnection(connectionString)) using (MySqlCommand sqlcmd = new MySqlCommand(sqlSelect, connection)) { sqlcmd.Parameters.AddWithValue("@Id", Id); sqlcmd.CommandTimeout = 0; await connection.OpenAsync(); using (MySqlDataReader reader = await sqlcmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var data = new MyData(); // 读取日期并转标准格式 DateTime myDate = reader.GetDateTime(0); data.MyDate = myDate.ToString("o"); // 读取Blob并转Base64 long blobLength = reader.GetBytes(1, 0, null, 0, 0); byte[] blobBytes = new byte[blobLength]; reader.GetBytes(1, 0, blobBytes, 0, (int)blobLength); data.MyBlob = Convert.ToBase64String(blobBytes); myList.Add(data); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } var json = JsonSerializer.Serialize(myList); return json; }
输出说明
修正后,Blob数据会以Base64字符串形式出现在JSON中,示例:
[{"MyDate":"2023-01-30T21:16:40.0000000","MyBlob":"SGVsbG8gV29ybGQh"}]
前端或其他消费者可通过Convert.FromBase64String将Base64字符串还原为二进制数据。
内容的提问来源于stack exchange,提问作者aka baka
相关产品推荐
相关产品推荐

