Sqlserver2000 Image Storage

Source: Internet
Author: User
Tags strong password

Microsoft's answer:

VB6 stores images to SQL Server:
Http://support.microsoft.com/default.aspx? SCID = KB; en-US; 258038

VB. NET saves images to SQL Server:
Http://support.microsoft.com/default.aspx? SCID = KB; en-US; 308042

C # saving images to SQL Server:
Http://support.microsoft.com/default.aspx? SCID = KB; en-US; 309158

 

 

This article summarizes how to save images to SQL Server in. Net winform and. Net webform (Asp.net) and read the display method.
1. Use Asp.net to upload images and store them in SQL Server. Then, read and display the images from SQL Server:
1) Upload and store the data to SQL Server
Database Structure
Create Table Test
{
Id identity (1, 1 ),
Fimage Image
}
Related stored procedures
Create proc updateimage
(
@ Updateimage Image
)
As
Insert into test (fimage) values (@ updateimage)
Go adds the following to the upphoto. aspx file:
<Input id = "upphoto" name = "upphoto" runat = "server" type = "file">
<Asp: button id = "btnadd" name = "btnadd" runat = "server" text = "Upload"> </ASP: button> the code file upphoto is added to the backend server. aspx. click the event processing code of the add btnadd button to CS:
Private void btnadd_click (Object sender, system. eventargs E)
{
// Obtain the image and convert the image to byte []
Httppostedfile upphoto = upphoto. postedfile;
Int upphotolength = upphoto. contentlength;
Byte [] photoarray = new byte [upphotolength];
Stream photostream = upphoto. inputstream;
Photostream. Read (photoarray, 0, upphotolength); // connect to the database
Sqlconnection conn = new sqlconnection ();
Conn. connectionstring = "Data Source = localhost; database = test; user id = sa; Pwd = sa"; sqlcommand cmd = new sqlcommand ("updateimage", Conn );
Cmd. commandtype = commandtype. storedprocedure; cmd. Parameters. Add ("@ updateimage", sqldbtype. Image );
Cmd. Parameters ["@ updateimage"]. value = photoarray; // if you do not want to use the stored procedure to add an image, change the above four sentences:
// String strsql = "insert into test (fimage) values (@ fimage )";
// Sqlcommand cmd = new sqlcommand (strsql, Conn );
// Cmd. Parameters. Add ("@ fimage", sqldbtype. Image );
// Cmd. Parameters ["@ fimage"]. value = photoarray; Conn. open ();
Cmd. executenonquery ();
Conn. Close ();
} 2) read and display from SQL Server
Add the following code to the image display area:
<Asp: Image id = "imgphoto" runat = "server" imageurl = "showphoto. aspx"> </ASP: Image> showphoto. aspx subject code:
Private void page_load (Object sender, system. eventargs E)
{
If (! Page. ispostback)
{
Sqlconnection conn = new sqlconnection ()
Conn. connectionstring = "Data Source = localhost; database = test; user id = sa; Pwd = sa"; string strsql = "select * from test where id = 2 "; // assume that the image with ID 2 is obtained.
Sqlcommand cmd = new sqlcommand (strsql, Conn); Conn. open ();
Sqldatareader reader = cmd. executereader ();
Reader. Read (); response. contenttype = "application/octet-stream ";
Response. binarywrite (byte []) Reader ["fimage"]);
Response. End ();
Reader. Close ();
}
} 2. Save the image to SQL Server in winform, read it from SQL Server, and display it in picturebox. 1) Save it to SQL Server
The database structure and stored procedures used are the same as above.
First, add an openfiledialog control in the form and name it ofdselectpic;
Then, add an open file button on the form and add the following Event code:
Stream MS;
Byte [] picbyte;
// Ofdselectpic. showdialog ();
If (ofdselectpic. showdialog () = dialogresult. OK)
{
If (MS = ofdselectpic. openfile ())! = NULL)
{
// MessageBox. Show ("OK ");
Picbyte = new byte [Ms. Length];
Ms. Position = 0;
Ms. Read (picbyte, 0, convert. toint32 (Ms. Length ));
// MessageBox. Show ("read finished! "); // Connect to the database
Sqlconnection conn = new sqlconnection ();
Conn. connectionstring = "Data Source = localhost; database = test; user id = sa; Pwd = sa"; sqlcommand cmd = new sqlcommand ("updateimage", Conn );
Cmd. commandtype = commandtype. storedprocedure; cmd. Parameters. Add ("@ updateimage", sqldbtype. Image );
Cmd. Parameters ["@ updateimage"]. value = picbyte; Conn. open ();
Cmd. executenonquery ();
Conn. Close (); Ms. Close ();
}
} 2) read and display in picturebox
First, add a picturebox named ptbshow
Then, add a button to add the following response event:
Sqlconnection conn = new sqlconnection ();
Conn. connectionstring = "Data Source = localhost; database = test; user id = sa; Pwd = sa"; string strsql = "select fimage from test where id = 1 "; sqlcommand cmd = new sqlcommand (strsql, Conn); Conn. open ();
Sqldatareader reader = cmd. executereader ();
Reader. read (); memorystream MS = new memorystream (byte []) Reader ["fimage"]); image = image. fromstream (MS, true); reader. close ();
Conn. Close (); ptbshow. Image = image; success ;-----------------------------------------------------------------------------------------------------------------------
using System.Data;
using System.Data.SqlClient;
using System.IO;
6. Double-clickButton1, And then add the following code toButton#clickEvent Handler.

NoteUID <User Name> must have permissions to perform these operations on the database.

{
SqlConnection con = new SqlConnection("Server=Darkover;uid=<username>;pwd=<strong password>;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(@"C:/winnt/Gone Fishing.BMP", FileMode.OpenOrCreate, FileAccess.Read);

byte[] MyData= new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

fs.Close();

da.Fill(ds,"MyImages");

DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();

myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");

con.Close();

}
7. Double-clickButton2, And then add the following code toButton2_clickEvent Handler.

NoteUID <User Name> must have permissions to perform these operations on the database.

{
SqlConnection con = new SqlConnection("Server=Darkover;uid=<username>;pwd=<strong password>;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");

byte[] MyData= new byte[0];

da.Fill(ds, "MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].Rows[0];

MyData = (byte[])myRow["imgField"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);

FileStream fs = new FileStream(@"C:/winnt/Gone Fishing2.BMP", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0,ArraySize);
fs.Close();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.