Skip to content

Instantly share code, notes, and snippets.

@huanlin
Last active December 19, 2015 13:38
Show Gist options
  • Save huanlin/5962961 to your computer and use it in GitHub Desktop.
Save huanlin/5962961 to your computer and use it in GitHub Desktop.
Read and Write BLOB fields using ADO.NET
private byte[] ReadBlob(int id)
{
byte[] result = null;
var conn = new SqlConnection("Your connection string");
conn.Open();
string sql = String.Format("select Photo from MyTable where ID={0}", id);
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
var reader = cmd.ExecuteReader();
if (reader.Read())
{
result = (byte[]) reader["Photo"];
}
return result;
}
private void WriteBlob(int id, byte[] data)
{
var conn = new SqlConnection("Your connection string");
conn.Open();
string sql = String.Format("update MyTable set Photo=@Photo where ID={0}", id);
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.Add("@Photo", SqlDbType.VarBinary, -1); // for VARBINARY(MAX) column.
cmd.Parameters["@Photo"].Value = data;
int updateCount = cmd.ExecuteNonQuery();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment