SQL String As Binary example

here is an easy piece - just dont try it with console cuz it doesnt support hebrew
a winform, 2 txt and a btn:

private void btnInsertAndRead_Click(object sender, EventArgs e)
{            
    SaveAsByteArray(txtInsert.Text);            
    txtRead.Text = LoadAsByteArray(3);        
}

void SaveAsByteArray(string str)
{
    SqlConnection con = new SqlConnection(
        "server=USER-PC;database=veterinar;Integrated Security=SSPI");
    try            
    {                
         System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
         byte[] strByte = encoding.GetBytes(str);
         SqlCommand cmd = new SqlCommand(
             "INSERT INTO dbo.tblBinary (strByte) VALUES (@Content)", con);
         SqlParameter p = new SqlParameter("@Content", System.Data.SqlDbType.Binary);
         p.Value = strByte;                
         cmd.Parameters.Add(p);                
         con.Open();                
         cmd.ExecuteNonQuery();
         con.Close();            
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message); con.Close();            
    }
}

string LoadAsByteArray(int id)
{
     SqlConnection con = new SqlConnection(
          "server=USER-PC;database=veterinar;Integrated Security=SSPI");
     try
     {
         SqlCommand cmd = new SqlCommand(
             "SELECT strByte FROM tblBinary WHERE id=" + id, con);
         con.Open();
         SqlDataReader r = cmd.ExecuteReader();
         r.Read();
         System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
         byte[] strByte = r.GetSqlBytes(0).Value;
         con.Close();
         return encoding.GetString(strByte);            
     }
     catch (Exception ex)
     {
           MessageBox.Show(ex.Message);
           con.Close();
           return "";
     }        
}

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

Asp.Net Ending Response options, Response.End() vs CompleteRequest()