zaterdag 3 oktober 2009

Inserting a file into a SQL BLOB column

One way to insert files into an SQL database. The file can be anything, an image, word document, etc. Just change the extension to your liking.
SqlCommand command = new SqlCommand();
SqlConnection connection = DatabaseManager.GetConnection();
string commandText = "INSERT INTO tablename VALUES(@Name, @Extension, @Blob)";
command.Connection = connection;
command.CommandText = commandText;
command.Parameters.Add(new SqlParameter("@Name ", fileName));
command.Parameters.Add(new SqlParameter("@Extension ", fileExtension));
FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Byte[] blob = new Byte[stream.Length];
stream.Read(blob, 0, blob.Length);
stream.Close();
stream.Dispose();
command.Parameters.Add(new SqlParameter("@Blob", blob));
command.ExecuteNonQuery();

Geen opmerkingen:

Een reactie posten