Last active
December 19, 2015 13:38
-
-
Save huanlin/5962961 to your computer and use it in GitHub Desktop.
Read and Write BLOB fields using ADO.NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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