首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 檔案存入資料庫完整實作(一):SQL Server 與 Access 雙資料庫支援

     編輯:關於C語言

將檔案存入資料庫是常見需求,本質是將檔案轉為二進位位元組陣列(byte[]),寫入對應欄位:SQL Server 用 Image 型別,Access 用 OLE Object 型別。

通用存檔流程

  1. 用 FileInfo + FileStream 讀取檔案為 byte[]
  2. 建立 SqlCommand/OleDbCommand 及參數化查詢
  3. 參數型別分別為 SqlDbType.Image / OleDbType.Binary
  4. 執行 ExecuteNonQuery() 完成寫入

SQL Server 版本

FileInfo fi = new FileInfo(fileName);
FileStream fs = fi.OpenRead();
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();

SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandType = CommandType.Text;
if (cn.State == ConnectionState.Closed) cn.Open();

cm.CommandText = "INSERT INTO " + tableName + "(" + fieldName + ") VALUES(@file)";
SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();

Access 版本(核心差異のみ標示)

OleDbCommand cm = new OleDbCommand();
cm.Connection = cn;
// ...
OleDbParameter spFile = new OleDbParameter("@file", OleDbType.Binary);
spFile.Value = bytes;
cm.Parameters.Add(spFile);

Web 檔案上傳直接存庫範例

string sql = "UPDATE t_mail SET attachfilename=@attachfilename, attachfile=@attachfile WHERE mailid=" + mailId;
SqlCommand myCommand = new SqlCommand(sql, new SqlConnection(ConnStr));

string path = fl_name.PostedFile.FileName;
string filename = path.Substring(path.LastIndexOf("\\") + 1);

myCommand.Parameters.Add("@attachfilename", SqlDbType.VarChar).Value = filename;
myCommand.Parameters.Add("@attachfile", SqlDbType.Image);

Stream fileStream = fl_name.PostedFile.InputStream;
int intFileSize = fl_name.PostedFile.ContentLength;
byte[] fileContent = new byte[intFileSize];
fileStream.Read(fileContent, 0, intFileSize);
fileStream.Close();

myCommand.Parameters["@attachfile"].Value = fileContent;
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();

最佳實踐提醒

  • 大檔案請採用 FileStream 分塊讀寫或 FILESTREAM 型別(SQL Server 2008+)
  • 務必使用參數化查詢防止 SQL 注入
  • using 區塊自動管理連線與資源釋放
  • 考慮將檔案存檔案系統,資料庫只存路徑,效能更佳
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved