當前位置:首頁 » 編程語言 » sqlserver存儲二進制數據
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

sqlserver存儲二進制數據

發布時間: 2022-09-03 01:03:41

『壹』 sqlServer存儲二進制圖片用什麼類型

存儲圖片:以二進制的形式存儲圖片時,要把資料庫中的欄位設置為Image數據類型(SQL Server),存儲的數據是Byte[]

『貳』 在SQL Server中,共使用了3種數據類型來存儲二進制數據,分別是______、______、

主要涉及 binary varbinary image 這三個欄位類型吧

請仔細了解sqlserver 各種數據類型

sql二進制數據類型詳解

如有疑問,及時溝通!

『叄』 sqlserver 二進制數據存儲問題

這種欄位我記得只要給個byte數組就可以了,不用轉移成binary

『肆』 Sqlserver資料庫存儲的圖片格式(二進制數據)怎麼顯示到頁面

1.將圖片以二進制存入資料庫
//保存圖片到資料庫
protected void Button1_Click(object sender, EventArgs e)
{
//圖片路徑
string strPath = "~/photo/03.JPG";
string strPhotoPath = Server.MapPath(strPath);
//讀取圖片
FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//存入
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) ";
strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length);
myComm.Parameters["@photoBinary"].Value = photo;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
}
2.讀取二進制圖片在頁面顯示
//讀取圖片
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myConn.Open();
SqlDataReader dr = myComm.ExecuteReader();
while (dr.Read())
{
byte[] photo = (byte[])dr["personPhoto"];
this.Response.BinaryWrite(photo);
}
dr.Close();
myConn.Close();

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
this.Response.BinaryWrite(photo);
3.設置Image控制項顯示從資料庫中讀出的二進制圖片
---------------------------------------------
SqlConnection myConn = new SqlConnection("Data Source=192.168.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
//圖片路徑
string strPath = "~/photo/wangwu.JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存圖片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
3.顯示圖片
this.Image1.ImageUrl = strPath;
4.GridView中ImageField以URL方式顯示圖片
--------------------------
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="圖片">
</asp:ImageField>
</Columns>
</asp:GridView>
5.GridView顯示讀出的二進制圖片
//樣板列
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="圖片">
</asp:ImageField>
<asp:TemplateField HeaderText="圖片">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
// System.ComponentModel.Container
string strPersonName = (string)DataBinder.Eval(e.Row.DataItem, "personName");
Image tmp_Image = (Image)e.Row.Cells[2].FindControl("Image1");
if (!System.Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "personPhoto")))
{
//
byte[] photo = (byte[])DataBinder.Eval(e.Row.DataItem, "personPhoto");
//圖片路徑
string strPath = "~/photo/" + strPersonName.Trim() + ".JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存圖片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
//顯示圖片
tmp_Image.ImageUrl = strPath;
}
}

『伍』 sqlserver 資料庫保存二進制數據流出錯,大蝦幫忙看下哪裡有問題,沒有分了,就這點分散了

轉換C盤命令是:開始-運行-cmd-convert c:/fs:ntfs
非系統盤轉換比較容易,直接右鍵格式化,選中NFS格式即可,或者用一般的格式轉換軟體都可以,一般不會造成不好影響。但系統盤(一般是C盤)就難度大了,重裝系統是最好的辦法,但你也可以試試Paragon Hard Disk Manager 這個軟體,但強烈不建議轉換系統盤,弄不好會出現莫名其妙的問題。所有盤轉化前都最好要備份好你的重要資料!

『陸』 sql sever中照片用什麼數據類型

如果你把照片文件保存到資料庫的話,那應該設置成image類型。

『柒』 .NET中如何循環遍歷一個文件夾中的圖片並將圖片以二進制的方式存入sqlserver資料庫

publicvoidToImg(Imageimg,Stringname)//插入圖片
{
#region上傳文件辦法
//FileStreamfs=newFileStream(Application.StartupPath+@"/gy.gif",FileMode.Open,FileAccess.Read);
//BinaryReaderbr=newBinaryReader(fs);
//byte[]photo=br.ReadBytes((int)fs.Length);
//br.Close();
//fs.Close();
#endregion

//把圖片轉換成二進制
MemoryStreamms=newMemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[]photo=ms.GetBuffer();
ms.Close();

//存儲欄位
OleDbCommandcmd=newOleDbCommand("INSERTINTO下單表(訂票人,識別碼)VALUES(@CategoryName,@Picture)",conn);
cmd.Parameters.Add("@CategoryName",OleDbType.VarChar,15).Value=name;
cmd.Parameters.Add("@Picture",OleDbType.Binary,photo.Length).Value=photo;
cmd.ExecuteNonQuery();
}
publicvoidPix(PictureBoxpx,Stringname)//顯示圖片
{
Stringsql="Select識別碼from下單表where訂票人='"+name+"'";
byte[]imagebytes=null;
OleDbCommandcom=newOleDbCommand(sql,conn);
OleDbDataReaderdr=com.ExecuteReader();
while(dr.Read())
{
imagebytes=(byte[])dr.GetValue(0);
}
MemoryStreamms=newMemoryStream(imagebytes);
Bitmapbmpt=newBitmap(ms);
px.Image=bmpt;
px.SizeMode=PictureBoxSizeMode.StretchImage;
}

這是資料庫讀取和存儲圖片的方法,至於遍歷文件夾,你自己找下例子吧,我是個懶人,太無聊的事情不做

『捌』 怎麼把圖片文件在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;
} }
}
}

『玖』 現有一個sql資料庫表如何讀取二進制內容

  1. 二進制數據由十六進制數表示,可以使用binary、varbinary和image數據類型存儲。

  2. binary固定長度(最多為8K)的二進制數據類型。

    binary[ ( n) ] 固定長度的 n個位元組二進制數據。N必須從 1 到 8,000。存儲空間大小為 n+4 位元組。

  3. varbinary可變長度(最多為8K)的二進制數據類型。

    varbinary[ ( n) ]n個

  4. 位元組變長二進制數據。n必須從 1 到 8,000。存儲空間大小為實際輸入數據長度 +4個位元組,而不是
    n個位元組。輸入的數據長度可能為 0 位元組。在 SQL-92 中varbinary的同義詞為binary
    varying。

  5. image用來存儲長度超過 8 KB 的可變長度的二進制數據。

  6. 除非數據長度超過 8KB,否則一般宜用 varbinary 類型來存儲二進制數據。一般用來存放
    Microsoft Word 文檔、Microsoft Excel 電子表格、包含點陣圖的圖像、圖形交換格式 (GIF) 文件和聯合圖像專家組 (JPEG)
    文件。

  7. 在 Image 數據類型中存儲的數據是以位字元串存儲的,不是由 SQL Server
    解釋的,必須由應用程序來解釋。例如,應用程序可以使用BMP、TIEF、GIF 和 JPEG 格式把數據存儲在 Image 數據類型中。

  8. 參考下列C# 代碼:

  9. privatevoidPage_Load(objectsender,System.EventArgse)
    {
    //gettheimageidfromtheurl
    stringImageId=Request.QueryString["img"];

    //buildourquerystatement
    stringsqlText="SELECTimg_data,img_contenttypeFROMImageWHEREimg_pk="+ImageId;

    SqlConnectionconnection=newSqlConnection(ConfigurationSettings.AppSettings["DSN"].ToString());
    SqlCommandcommand=newSqlCommand(sqlText,connection);

    //
    connection.Open();
    SqlDataReaderdr=command.ExecuteReader();
    if(dr.Read())//yupwefoundourimage
    {
    Response.ContentType=dr["img_contenttype"].ToString();
    Response.BinaryWrite((byte[])dr["img_data"]);
    }
    connection.Close();
    }
    }

『拾』 如何將二進制數組存入sqlserver中,語句

--創建表
create table test(col varbinary(4000))
go

--創建存儲過程
create procere sp_savaBinary(@binary varbinary(4000))
as
insert into test values(@binary)
go

--調用存儲過程插入數據
declare @binary varbinary(4000)
set @binary = cast( '12sfasfasfasf ' as varbinary(4000))
exec sp_savaBinary @binary