当前位置:首页 » 操作系统 » 数据库保存二进制

数据库保存二进制

发布时间: 2023-09-02 15:03:25

① 怎么把图片文件在sql server数据库中保存为二进制记录(注:不是用图片路径),最好有源代码。

首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,
ImageDescription Column为储蓄图象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:
CREATE TABLE [dbo].[ImageStore] (
[ImageID] [int] IDENTITY (1, 1) NOT NULL ,
[ImageData] [image] NULL ,
[ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 向数据库中存入图片:using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;namespace UpLoadFile
{
/// <summary>
/// Summary description for UpLoadImage.
/// </summary>
public class UpLoadImage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.WebControls.Label txtMessage;
protected System.Web.UI.WebControls.TextBox txtDescription;
protected System.Web.UI.HtmlControls.HtmlTable Table1;
protected System.Web.UI.HtmlControls.HtmlInputFile UP_FILE;//HtmlControl、WebControls控件对象
protected Int32 FileLength = 0;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
this.Load += new System.EventHandler(this.Page_Load); }
#endregion private void btnUpload_Click(object sender, System.EventArgs e)
{
HttpPostedFile UpFile = this.UP_FILE.PostedFile; //HttpPostedFile对象,用于读取图象文件属性
FileLength = UpFile.ContentLength; //记录文件长度
try
{
if (FileLength == 0)
{ //文件长度为零时
txtMessage.Text = "<b>请你选择你要上传的文件</b>";
}
else
{
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = UpFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
SqlConnection Con = new SqlConnection("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = txtDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = UpFile.ContentLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
}
}
catch (Exception ex)
{
txtMessage.Text = ex.Message.ToString();
}

} }
}
将数据库中的图片数据读出来显示:using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;namespace UpLoadFile
{
/// <summary>
/// Summary description for ReadImage.
/// </summary>
public class ReadImage : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
string id = Request.QueryString["ImgID"]; //得到图片的ID if (id != ""&& id != null && id != string.Empty)
{
ShowImage( id);
}
}
} #region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load); }
#endregion public void ShowImage(string id)
{
int ImgID = Convert.ToInt32(id); //ImgID为图片ID
//建立数据库链接
SqlConnection Con = new SqlConnection("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
try
{
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
Con.Close();
}
catch
{
Response.Write("<script>alert('该图片不存在');</script>");
return;
} }
}
}

② 文件转二进制流保存到数据库中是不是比较节省数据库空间

以二进制方式保存主要是考虑数据库字段存储大小的问题,及方便性,不见得节数据库空间。

③ 怎么在mysql中存储二进制文件

php脚本为例。PHP一般只支持小于2M的文件,假如要存取大于2M的文件,那就要进系统方面的设置了。具体操作如下:


首先创建测试表testtable

CREATETABLEtesttable(idINT(5)NOTNULLAUTO_INCREMENTPRIMARYKEY,filenameCHAR(255),dataLONGBLOB);


将文件存入表中使用如下PHP代码

<?php
mysql_connect("localhost","root","password");//连接数据库
mysql_select_db("database");//选定数据库
$filename=""//这里填入二进制文件名
$data=addslashes(fread(fopen($filename,"r"),filesize($filename)));//打开文件并规范化数据存入变量$data中
$result=mysql_query("INSERTINTOtesttable(filename,data)VALUES('$filename','$data')");//数据插入到数据库test表中
mysql_close();
?>


从表中取回文件,使用如下PHP代码

<?php
if($id){
mysql_connect("localhost","root","password");
mysql_select_db("database");
$filename=""//这里填入二进制文件名
$query="=$filename";
$result=mysql_query($query);
$data=mysql_result($result,0,"data");
?>

④ 如何将txt,doc等文件以二进制形式保存在数据库中

private int WriteToDB(string strName, string strType, ref byte[] Buffer)
{
int nFileID = 0;

// Create connection
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

// Create Adapter
OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);

// We need this to get an ID back from the database
dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

// Create and initialize CommandBuilder
OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

// Open Connection
dbConn.Open();

// New DataSet
DataSet dbSet = new DataSet();

// Populate DataSet with data
dbAdapt.Fill(dbSet, "tblFile");

// Get reference to our table
DataTable dbTable = dbSet.Tables["tblFile"];

// Create new row
DataRow dbRow = dbTable.NewRow();

// Store data in the row
dbRow["FileName"] = strName;
dbRow["FileSize"] = Buffer.Length;
dbRow["ContentType"] = strType;
dbRow["FileData"] = Buffer;

// Add row back to table
dbTable.Rows.Add(dbRow);

// Update data source
dbAdapt.Update(dbSet, "tblFile");

// Get newFileID
if( !dbRow.IsNull("FileID") )
nFileID = (int)dbRow["FileID"];

// Close connection
dbConn.Close();

// Return FileID
return nFileID;
}
写入库。
private void ShowTheFile(int FileID)
{
// Define SQL select statement
string SQL = "SELECT FileSize, FileData, ContentType FROM tblFile WHERE FileID = "
+ FileID.ToString();

// Create Connection object
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

// Create Command Object
OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

// Open Connection
dbConn.Open();

// Execute command and receive DataReader
OleDbDataReader dbRead = dbComm.ExecuteReader();

// Read row
dbRead.Read();

// Clear Response buffer
Response.Clear();

// Set ContentType to the ContentType of our file
Response.ContentType = (string)dbRead["ContentType"];

// Write data out of database into Output Stream
Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

// Close database connection
dbConn.Close();

// End the page
Response.End();
}
读出

⑤ 数据库中存储二进制文件的查询效率问题

你所谓的二进制数据文件针对的应该是大对象,一般而言,不会使用到这种存储方式。不过说查询效率,在对大对象进行查询时,像ORACLE,就是给数据文件增加了一个头,用以查询时的定位。而对于大数据的文本文件,比如CLOB,它提供了其他的方式让你来进行数据查询。而你所说的存在其他的字段,那么,如果你存储的是文本文件而非音频视频的话,建议你采用CLOB而非BLOB……另外,就查询效率而言,没有什么固定的方式是最好的,只有针对你的应用,采用最合适的数据库架构才是最优的。在查询效率这点上,建议你看看数据库的簇集,索引,分区/多文件组(oracle是分区,sql server就是多文件组了),这些如果使用恰当的话,可以提高查询效率……

⑥ 以二进制形式保存文件到数据库 有什么优点缺点呢请指教 数据库是mysql,文件类型是doc和txt

优点,不用单独管理文件了呗,文件数据都在数据库里呢。用户想访问文件的话,你就可以做一些权限检查什么的,通过才给它取数据。

缺点,数据库稍微有些压力呗~~~~数据库文件会变大~~~

热点内容
缓存网易音乐在内存卡 发布:2025-03-01 00:46:24 浏览:123
零基础编程培训学费要多少 发布:2025-03-01 00:46:13 浏览:32
联通50兆上传速度 发布:2025-03-01 00:41:16 浏览:777
老师脚本本 发布:2025-03-01 00:41:11 浏览:624
初中猫脚本 发布:2025-03-01 00:40:38 浏览:485
车船编程 发布:2025-03-01 00:36:23 浏览:904
服务器已禁用设备是什么意思 发布:2025-03-01 00:25:55 浏览:211
python下载html 发布:2025-03-01 00:16:55 浏览:956
ftp未找到命令 发布:2025-03-01 00:15:54 浏览:942
vivo怎么清除账户密码 发布:2025-03-01 00:10:03 浏览:115