c# - Store image in database and retrieve it -



c# - Store image in database and retrieve it -

my code inserting image in database follows:

memorystream ms =new memorystream(); byte[] photobyte=null; photobyte=ms.toarray(); picturebox1.image.save(ms, imageformat.jpeg); photobyte =ms.toarray(); str = "insert experimmm values('" + photobyte + "','" + textbox1.text + "')"; conn.open(); cmd.connection = conn; cmd.commandtext = str; cmd.executenonquery(); conn.close();

which going well. can see binary info in ma database table <binary data> code retrieving info is:

str ="select * experimmm id = '" +textbox2.text + "'"; conn.open(); cmd.connection = conn; cmd.commandtext = str; dr = cmd.executereader(); if (dr.read()) { label1.text = dr.getvalue(1).tostring(); byte[] photobyte = (byte[])dr.getvalue(0); memorystream mem = new memorystream(photobyte, 0, photobyte.length); //but error takes place on next line "parameter not valid." picturebox2.image = image.fromstream(mem); } conn.close();

i'm using visual studio 10 , c# ,sql server 2005

it possible of course of study store images in db. not recommended. improve store them in file system.

your code bit messy. next improve example.

memorystream ms =new memorystream(); byte[] photobyte=null; picturebox1.image.save(ms, imageformat.jpeg); photobyte =ms.toarray(); // i'm not sure whether able create sql concating string str = "insert experimmm values('@photobytes','@mytextvalue')"; // have parametrize query cmd.parameters.addwithvalue("photobytes", photobyte); // helps avoid syntactical corruption in case of ' , sql injection cmd.parameters.addwithvalue("mytextvalue", textbox1.text ); conn.open(); cmd.connection = conn; cmd.commandtext = str; cmd.executenonquery(); conn.close();

when retrieve utilize binary author in handler

namespace testns { public class myhttphandler : ihttphandler { // override processrequest method. public void processrequest(httpcontext context) { // preparations, i.e. querystring or var conn = new sqlconnection("your connectionstring"); var command = new sqlcommand("your sql retrieval of bytes", conn); conn.open(); var info = (byte[])command.executescalar(); conn.close(); context.response.binarywrite(data); } public boolean isreusable { { homecoming false; } } } }

c# visual-studio-2010 sql-server-2005

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -