Lưu file ảnh vào sql server

     
Đừng nghĩ bạn được bao nhiêu điểm. Đừng nghĩ bàn sinh hoạt ở trường nào. Đừng nghĩ bạn giỏi nghiệp các loại gì. Hãy nghĩ: MÌNH CÓ GÌ trong ĐẦU.

Bạn đang xem: Lưu file ảnh vào sql server


Pages

C#CTDLJ2EEEJBEJB 2.x với NetBeans 6.7.1 và JBoss AS 4.23GAEJB 3Java MailJMSRMIJavaLập trình java cănbảnBài tập chương4GUI applicationLập trình java nângcaoCác nhà đềkhácJDBC – Java DatabaseConnectivityJPA – Java PersistenceAPINetworkingMobile DevAndroid developmentMy GardenÂm nhạcSeminarMy ProjectsSEVisual BasicWebASP.NetHost ứng dụngwebJSF – Java ServerFaceJBoss RichFacesRichFaces: Logon cùng RegistrationapplicationJSPServlet programmingStrutsWeb servicesC# website servicesJava web servicesTạo web services cùng với JAX-WS 2.0 với Java SE 6PlatformXMLJXML – JSPXSLT Examples

Blog Stats

2,960,667 hits

Email Subscription


Enter your thư điện tử address lớn subscribe to this blog & receive notifications of new posts by email.

Email Address:

Sign me up!


Join 2,200 other subscribers
Lưu hình hình ảnh vàodatabase

Trong nội dung bài viết này tôi đã hướng dẫn bạn cách chèn hình hình ảnh trực tiếp vào database. Biện pháp này tuy làm cho database lớn/nặng nhưng nó cũng giải quyết rất nhiều sự việc trong quá trình lập trình.Ở đây, csdl tôi thực hiện là ms Access cùng MS SQLserver.Cách 1: Database là Access1. Bạn tạo 1 tệp tin access mang tên TestDB.mdb phía bên trong thư mục bindebug của ứng dụng(chỗ không giống cũng không sao, tùy).Tạo 1 bảng mang tên tblSinhvien có cấu trúc như sau:

Tên fieldKiểu dữ liệu
MSSVText(15)
hinhAnhOLE Object

2. Chế tạo 1 Windows size Application Project bao gồm tên Store_Retrieve_Image_From_DB.

Xem thêm: Bảng Mã Lỗi Máy Giặt Toshiba Và Cách Khắc Phục, Bảng Mã Lỗi Máy Giặt Toshiba Và Cách Xử Lý

3. Tạo lớp mang tên ConnectDB.cs với nội dung sau:

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.OleDb;namespace Store_Retrieve_Image_From_DBpublic class ConnectDBprivate OleDbConnection con;private DataSet ds;private OleDbDataAdapter daSV;/// /// cách tiến hành constructor khởi tạo kết nối đến database/// public ConnectDB()trycon = new OleDbConnection();con.ConnectionString = “Provider=microsoft.jet.OLEDB.4.0;Data Source=”+System.Windows.Forms.Application.StartupPath+”\TestDB.mdb”;con.Open();catch (Exception)throw;/// /// phủ về toàn bộ các mẫu tin vào bảng tblSinhvien/// /// public DataSet GetTable()ds = new DataSet();daSV = new OleDbDataAdapter(“select * from tblSinhvien”, con);daSV.Fill(ds, “tblSinhvien”);return ds;/// /// update các đổi khác của tín đồ dùng/// public void UpdateSV()tryOleDbCommandBuilder bd = new OleDbCommandBuilder(daSV);daSV.Update(ds, “tblSinhvien”);catch (Exception)

throw;

Lớp này dùng để đọc tài liệu từ database cũng như cập nhật dữ liệu xuống database.

3. Xây cất MainForm như hình

*
4. Code mang đến Form:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Windows.Forms;namespace Store_Retrieve_Image_From_DBpublic partial class MainForm : Formprivate ConnectDB conDB;private DataSet ds = new DataSet();private BindingSource bs;private DataTable dtSV;

public MainForm()InitializeComponent();

private void MainForm_Load(object sender, EventArgs e)tryconDB = new ConnectDB();ds = conDB.GetTable();dtSV = ds.Tables<“tblSinhvien”>;bs = new BindingSource(ds, “tblSinhvien”);bs.CurrentItemChanged += new EventHandler(bs_CurrentItemChanged);dataGridView1.DataSource = bs;bindingNavigator1.BindingSource = bs;catch (Exception ex)MessageBox.Show(ex.ToString());/// /// Sự kiện xảy ra khi binding source bao gồm sự thay đổi do người/// cần sử dụng chọn các dòng bên trên lưới hặc nhấn những nút di chuyển./// /// /// void bs_CurrentItemChanged(object sender, EventArgs e)DataRowView row = (DataRowView)bs.Current;tryByte<> i = (byte<>)row<“hinhAnh”>;MemoryStream stmBLOBData = new MemoryStream(i);picHinhAnh.Image = Image.FromStream(stmBLOBData);catch (Exception ex)picHinhAnh.Image = null;MessageBox.Show(ex.ToString());

private void btnLuu_Click(object sender, EventArgs e)tryDataRow dr = dtSV.NewRow();dr<“MSSV”> = txtMSSV.Text;if (picHinhAnh.Image != null)MemoryStream ms = new MemoryStream();picHinhAnh.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Byte<> bytBLOBData = new Byte;ms.Position = 0;ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));dr<“hinhAnh”> = bytBLOBData;dtSV.Rows.Add(dr);

conDB.UpdateSV();catch (Exception ex)MessageBox.Show(ex.ToString());

private void btnLoadHinh_Click(object sender, EventArgs e)*.GIF”;if (dlg.ShowDialog(this) == DialogResult.OK)picHinhAnh.Image = Image.FromFile(dlg.FileName);

Chú ý:

Để đọc tài liệu hình hình ảnh ra ta cần sử dụng 1 mảng Byte để đựng giá trị của field hình ảnh. Sau đó muốn hiển thị nó lên PictureBox ta đề nghị dùng MemoryStream để mang ra:

Byte<> i = (byte<>)row<"hinhAnh">;MemoryStream stmBLOBData = new MemoryStream(i);picHinhAnh.Image = Image.FromStream(stmBLOBData);

Để cập nhật dữ liệu vào db, ta đề nghị lấy hình ảnh từ PictureBox vào 1 MemoryStream:

MemoryStream ms = new MemoryStream();picHinhAnh.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Rồi tiếp nối mới gửi nó thành mảng Byte rồi cung cấp cho 1 datarow để update xuống database.

Byte<> bytBLOBData = new Byte;ms.Position = 0;ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));dr<"hinhAnh"> = bytBLOBData;dtSV.Rows.Add(dr);

Chạy ứng dụng, kết quả như hình sau:

*

Cách 2: Database là Microsoft SQL Server

1. Chế tạo ra database tất cả tên: TestImageDB với 1 bảng có tên tblImages với có kết cấu như hình sau:

*
2. Chế tạo ra stored project mang tên InsertImage với sql script như sau:

CREATE PROCEDURE InsertImage
blobdata)

3. Chế tạo ra Windows form Application Project có tên AnotherWay.

4. Tạo lớp ConnectDB.cs gồm nội dung như sau:

using System;using System.Collections.Generic;using System.IO;using System.Data;using System.Data.SqlClient;

namespace AnotherWayclass ConnectDBprivate SqlConnection conn;private string connectionString = “Server=.;UID=sa;PWD=;Initial Catalog=TestImageDB”;

public ConnectDB()conn = new SqlConnection(connectionString);

public void StorePicture(string filename)byte<> imageData = null;// Read the file into a byte arrayusing (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))imageData = new Byte;fs.Read(imageData, 0, (int)fs.Length);using (SqlConnection conn = new SqlConnection(connectionString))SqlCommand cmd = new SqlCommand(“InsertImage”, conn);cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.AddWithValue(“
blobdata”>.Direction = ParameterDirection.Input;// Store the byte array within the image fieldcmd.Parameters<“
blobdata”>.Value = imageData;conn.Open();cmd.ExecuteNonQuery();

public byte<> RetrieveImage()byte<> imageData = null;conn.Open();SqlCommand cmd = new SqlCommand(“select blobdata from tblImages”, conn);// Assume previously established command and connection// The command SELECTs the IMAGE column from the table

using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))reader.Read();// Get size of image data – pass null as the byte array parameterlong bytesize = reader.GetBytes(0, 0, null, 0, 0);// Allocate byte array khổng lồ hold image dataimageData = new byte;long bytesread = 0;int curpos = 0;int chunkSize = 1;while (bytesread // chunkSize is an arbitrary application defined valuebytesread += reader.GetBytes(0, curpos, imageData, curpos, chunkSize);curpos += chunkSize;conn.Close();// byte array ‘imageData’ now contains BLOB from databasereturn imageData;

5. Kiến tạo Form như hình
*

6. Code đến Form:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Windows.Forms;

namespace AnotherWaypublic partial class Form1 : Formprivate ConnectDB conDB;public Form1()InitializeComponent();conDB = new ConnectDB();

private void button1_Click(object sender, EventArgs e)GIF Files(*.GIF)

private void button2_Click(object sender, EventArgs e)byte<> img = conDB.RetrieveImage();MemoryStream str = new MemoryStream(img);pictureBox1.Image = Image.FromStream(str);

7. Thực thi

qqlive| j88