Thứ Bảy, 23 tháng 11, 2019

Lưu trữ hoặc lưu tệp / tài liệu trong cơ sở dữ liệu SQL Server bằng C #

Đăng Bởi: Admin - tháng 11 23, 2019 - 0 Bình Luận

Lưu trữ tệp trong SQL Server

https://shabdar.org/sql-server/121-store-or-save-files-in-sql-server-database-using-c.html
http://www.shabdar.org/c-sharp/83-connecting-to-mysql-database-using-c-and-net.html
http://www.shabdar.org/sql-server/105-store-save-images-in-sql-server.html



Giới thiệu

Mẫu này sẽ giải thích cho bạn cách bạn có thể lưu trữ tệp hoặc tài liệu trong cơ sở dữ liệu SQL Server. Nói chung, không nên lưu trữ tệp trong cơ sở dữ liệu vì nó có thể phát triển cơ sở dữ liệu nhanh chóng và có thể gây ra hiệu suất chậm hơn của cơ sở dữ liệu và máy chủ. Tốt nhất bạn nên sử dụng hệ thống tập tin để lưu trữ tập tin. Nhưng có thể có các kịch bản mà bạn có thể muốn lưu trữ các tệp trong cơ sở dữ liệu.
Lưu trữ tệp trong SQL Server
Tập tin mới

Cách lưu trữ tệp trong cơ sở dữ liệu SQL Server

Để lưu trữ một tệp trong máy chủ sql, bạn cần đọc dữ liệu tệp vào một mảng byte. Khi bạn có dữ liệu tệp trong mảng byte, bạn có thể dễ dàng lưu trữ dữ liệu tệp này trong máy chủ sql bằng các tham số sql. Mã sau giải thích cho bạn làm thế nào để làm điều này.
01.private void cmdSave_Click(object sender, EventArgs e)
02.{
03.try
04.{
05.//Read File Bytes into a byte array
06.byte[] FileData = ReadFile(txtFilePath.Text);
07. 
08.//Initialize SQL Server Connection
09.SqlConnection CN = new SqlConnection(txtConnectionString.Text);
10. 
11.//Set insert query
12.string qry = "insert into FilesStore (OriginalPath,FileData) values(@OriginalPath, @FileData)";
13. 
14.//Initialize SqlCommand object for insert.
15.SqlCommand SqlCom = new SqlCommand(qry, CN);
16. 
17.//We are passing Original File Path and file byte data as sql parameters.
18.SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", (object)txtFilePath.Text));
19.SqlCom.Parameters.Add(new SqlParameter("@FileData", (object)FileData));
20. 
21.//Open connection and execute insert query.
22.CN.Open();
23.SqlCom.ExecuteNonQuery();
24.CN.Close();
25. 
26.//Close form and return to list or Files.
27.this.Close();
28.}
29.catch(Exception ex)
30.{
31.MessageBox.Show(ex.ToString());
32.}
33.}
Đoạn mã sau giải thích cách đọc dữ liệu tệp trong một mảng byte.
01.//Open file in to a filestream and read data in a byte array.
02.byte[] ReadFile(string sPath)
03.{
04.//Initialize byte array with a null value initially.
05.byte[] data = null;
06. 
07.//Use FileInfo object to get file size.
08.FileInfo fInfo = new FileInfo(sPath);
09.long numBytes = fInfo.Length;
10. 
11.//Open FileStream to read file
12.FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
13. 
14.//Use BinaryReader to read file stream into byte array.
15.BinaryReader br = new BinaryReader(fStream);
16. 
17.//When you use BinaryReader, you need to supply number of bytes to read from file.
18.//In this case we want to read entire file. So supplying total number of bytes.
19.data = br.ReadBytes((int)numBytes);
20. 
21.//Close BinaryReader
22.br.Close();
23. 
24.//Close FileStream
25.fStream.Close();
26. 
27.return data;
28.}

Cách đọc byte dữ liệu tệp từ bảng SQL Server

Để đọc tệp từ SQL Server, trước tiên hãy chuẩn bị bộ dữ liệu sẽ chứa dữ liệu từ bảng SQL Server. Liên kết dữ liệu này với một điều khiển Gridview trên mẫu.
01.//Get table rows from sql server to be displayed in Datagrid.
02.void GetFilesFromDatabase()
03.{
04.try
05.{
06.//Initialize SQL Server connection.
07.SqlConnection CN = new SqlConnection(txtConnectionString.Text);
08. 
09.//Initialize SQL adapter.
10.SqlDataAdapter ADAP = new SqlDataAdapter("Select FileId,OriginalPath,FileData from FilesStore", CN);
11. 
12.//Initialize Dataset.
13.DS = new DataSet();
14. 
15.//Fill dataset with FilesStore table.
16.ADAP.Fill(DS, "FilesStore");
17. 
18.//Fill Grid with dataset.
19.dataGridView1.DataSource = DS.Tables["FilesStore"];
20.}
21.catch(Exception ex)
22.{
23.MessageBox.Show(ex.ToString());
24.}
25.}
Khi bạn có dữ liệu hình ảnh trong tập dữ liệu DS, hãy lấy dữ liệu tệp từ một mảng byte.
1.//Get File data from dataset row.
2.byte[] FileData = (byte[])DS.Tables["FilesStore"].Rows[SelectedRow]["FileData"];
Cuối cùng lưu dữ liệu mảng byte vào một tệp
1.//Write file data to selected file.
2.using (FileStream fs = new FileStream(FileName, FileMode.Create))
3.{
4.fs.Write(FileData, 0, FileData.Length);
5.fs.Close();
6.}

Cách tải xuống và chạy chương trình

  • Tải mẫu từ liên kết trên đầu trang. Trích xuất trong một thư mục.
  • Khôi phục cơ sở dữ liệu SQL Server từ thư mục con Cơ sở dữ liệu SQL.
  • Nếu bằng cách nào đó bạn không thể khôi phục cơ sở dữ liệu được cung cấp, bạn có thể tạo bảng cần thiết bằng cách sử dụng tập lệnh (SQLScript.txt) được cung cấp trong thư mục Cơ sở dữ liệu SQL.
  • Mở giải pháp và chạy nó. Thay đổi chuỗi kết nối cho cơ sở dữ liệu của bạn.
  • Nhấp vào nút Kết nối. Để thêm tệp mới vào cơ sở dữ liệu, nhấp vào nút Tệp mới . Nhấp vào nút Duyệt trong cửa sổ Tệp mới để chọn tệp. Sau đó bấm vào Save để lưu nó.

Yêu cầu

  • Visual Studio.Net 2008
  • .Net Framework 2.0
  • Cơ sở dữ liệu MS SQL Server (mọi phiên bản)

Phản Hồi Độc Giả

Một số lưu ý khi bình luận

Mọi bình luận sai nội quy sẽ bị xóa mà không cần báo trước (xem nội quy)

Bấm Thông báo cho tôi bên dưới khung bình luận để nhận thông báo khi admin trả lời

Để bình luận một đoạn code, hãy mã hóa code trước nhé