Lưu file ảnh vào sql server
Recent Posts
Archives
ArchivesSelect Month August 2011 (1) March 2011 (1) June 2010 (1) January 2010 (1) September 2009 (1) May 2009 (1) March 2009 (1) December 2008 (3) November 2008 (1) October 2008 (1) October 2007 (1)Subscribe
Các đánh giá ngay sát đây
Các trang được yêu thích
Đừng nghĩ về bạn được bao nhiêu điểm. Đừng suy nghĩ bàn sinh hoạt làm việc ngôi trường làm sao. Đừng suy nghĩ chúng ta tốt nghiệp một số 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 cùng với NetBeans 6.7.1 và Jmonster AS 4.23GAEJB 3Java MailJMSRMIJavaLập trình java cănbảnNhững bài tập chương4GUI applicationLập trình java nângcaoCác chủ đềkhácJDBC – Java DatabaseConnectivityJPA – Java PersistenceAPINetworkingSmartphone DevAndroid developmentMy GardenÂm nhạcSeminarMy ProjectsSEVisual BasicWebASP..NetHost ứng dụngwebJSF – Java ServerFaceJmonster RichFacesRichFaces: Logon với RegistrationapplicationJSPServlet programmingStrutsWeb servicesC# Web servicesJava Web servicesTạo Web services với JAX-WS 2.0 với Java SE 6PlatformXMLJXML – JSPXSLT ExamplesBlog Stats
2,909,065 hitsThư điện tử Subscription
Enter your gmail address to lớn subscribe to lớn this blog and receive sầu notifications of new posts by email.
Join 2,200 other followers
E-Mail Address:
Sign me up!
Lưu hình ảnh vàodatabase
Trong bài viết này tôi đã giải đáp các bạn phương pháp cyếu hình hình họa thẳng vào database. Cách này Mặc dù tạo cho database lớn/nặng nề nhưng nó cũng giải quyết và xử lý không hề ít vấn đề vào quy trình lập trình sẵn.Tại phía trên, csdl tôi áp dụng là ms Access với MS SQLVPS.Cách 1: Database là Access1. quý khách chế tạo ra 1 file access có tên TestDB.mdb nằm trong thư mục bindebug của ứng dụng(nơi khác cũng ko có gì, tùy).Tạo 1 bảng mang tên tblSinhvien có cấu tạo như sau:
MSSV | Text(15) |
hinhAnh | OLE Object |
2. Tạo 1 Windows Form Application Project gồm tên Store_Retrieve_Image_From_DB.
Xem thêm: Code Lấy Số Điện Thoại Khi Truy Cập Website, Lấy Số Điện Thoại Khách Hàng Truy Cập Website
3. Tạo lớp có 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;/// /// Phương thơm thức constructor khởi tạo thành kết nối đến database/// public ConnectDB()trybé = new OleDbConnection();nhỏ.ConnectionString = “Provider=microsoft.jet.OLEDB.4.0;Data Source=”+System.Windows.Forms.Application.StartupPath+”\TestDB.mdb”;con.Open();catch (Exception)throw;/// /// Lấp về tất cả các mẫu mã 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;/// /// Cập nhật những chuyển đổi của bạn dùng/// public void UpdateSV()tryOleDbCommandBuilder bd = new OleDbCommandBuilder(daSV);daSV.Update(ds, “tblSinhvien”);catch (Exception) throw; |
3. Thiết kế MainForm nhỏng hình

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 lúc binding source bao gồm sự biến đổi do người/// cần sử dụng lựa chọn các cái trên lưới hặc nhấn những nút dịch 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 conDB.UpdateSV();catch (Exception ex)MessageBox.Show(ex.ToString()); private void btnLoadHinh_Click(object sender, EventArgs e)*.JPG |
Để gọi tài liệu hình hình ảnh ra ta sử dụng 1 mảng Byte nhằm cất quý hiếm của field hình ảnh. Sau đó muốn hiển thị nó lên PictureBox ta buộc phải dùng MemoryStream để lấy ra:
Byte<> i = (byte<>)row<"hinhAnh">;MemoryStream stmBLOBData = new MemoryStream(i);picHinhAnh.Image = Image.FromStream(stmBLOBData);
Để cập nhật tài liệu vào db, ta đề nghị mang hình họa từ PictureBox vào 1 MemoryStream:
MemoryStream ms = new MemoryStream();picHinhAnh.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Rồi sau đó bắt đầu gửi nó thành mảng Byte rồi cung cấp cho 1 datarow nhằm update xuống database.
Xem thêm: Cách Tạo Server Minecraft Không Cần Hamachi (With Pictures), Cách Thiết Lập Minecraft Server Với Hamachi
Byte<> bytBLOBData = new Byte
Chạy áp dụng, hiệu quả nhỏng hình sau:

Cách 2: Database là Microsoft SQL Server
1. Tạo database có tên: TestImageDB với một bảng mang tên tblImages cùng có cấu tạo nhỏng hình sau:

CREATE PROCEDURE InsertImage blobdata) |
3. Tạo Windows Form Application Project mang tên AnotherWay.
4. Tạo lớp ConnectDB.cs bao gồm câu chữ nhỏng 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.xuất hiện, FileAccess.Read))imageData = new Byte public byte<> RetrieveImage()byte<> imageData = null;conn.Open();SqlCommvà cmd = new SqlCommand(“select blobdata from tblImages”, conn);// Assume previously established commvà và connection// The command SELECTs the IMAGE column from the table using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))reader.Read();// Get form size of image data – pass null as the byte array parameterlong bytekích thước = reader.GetBytes(0, 0, null, 0, 0);// Allocate byte array to lớn hold image dataimageData = new byte |

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); |