C# convert sql blob type to plain string

FredGrit發表於2024-09-01

Blob stands for binary large object

 byte[] bytesArr= (byte[])rows[i]["congest"]; 
 bk.Congest = Encoding.UTF8.GetString(bytesArr)
public static DataSet GetSQLDataset(string selectSQL)
{
    DataSet ds = new DataSet();
    using (MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn))
    {
        da.Fill(ds);
    }
    return ds;
}



 private void LoadCmdExecuted(object obj)
 {
     string selectSQL = "select * from  mt;";
     DataSet ds=DBHelper.GetSQLDataset(selectSQL);
     if(ds!=null && ds.Tables!=null && ds.Tables.Count>0)
     {
         var rows=ds.Tables[0].Rows;
         int rowsCount = rows.Count;
         MessageBox.Show($"Get {rowsCount}");
         List<Book> booksList = new List<Book>();
         var colsCnt=ds.Tables[0].Columns.Count;
         int id = 0;
        
         for(int i=0;i<rowsCount;i++)
         {
             Book bk = new Book();
             if (Int32.TryParse(rows[i]["id"]?.ToString(), out id))
             {
                 bk.Id = id;
                 bk.Name = rows[i]["name"]?.ToString();
                 bk.Author = rows[i]["author"]?.ToString();
                 //bk.Congest = rows[i]["congest"]?.ToString();
                 byte[] bytesArr = (byte[])rows[i]["congest"];
                 if(bytesArr!=null && bytesArr.Any())
                 {
                     bk.Congest = Encoding.UTF8.GetString(bytesArr);
                 }                        
                 bk.Comment= rows[i]["comment"]?.ToString(); 
                 bk.Content = rows[i]["content"]?.ToString();
                 bk.Summary = rows[i]["summary"]?.ToString();
                 bk.ImgUrl = rows[i]["imgurl"]?.ToString();
                 bk.Title = rows[i]["title"]?.ToString();
                 bk.Topic = rows[i]["topic"]?.ToString();
             }
             booksList.Add(bk);
         }
         BooksCollection = new ObservableCollection<Book>(booksList);
     }
 }

相關文章