Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,037

HOME > ASP.NET > ASP.NET Microsoft SQL Server (System.Data.SqlClient) > ASP.NET SQL Server BLOB Binary Data and Parameterized Query



Clound SSD Virtual Server

ASP.NET SQL Server BLOB Binary Data and Parameterized Query

ASP.NET SQL Server BLOB Binary Data and Parameterized Query เขียน ASP.NET เพื่อจัดการข้อมูลใน Database SQL Server ผ่าน Binary Data ในรูปแบบของ BLOB โดยคำสั่ง Execute Add/Insert/Update และ Delete ใช้รูปแบบการส่งข้อมูล Parameter เพื่อไช้ในการ Query Data (Using Parameterized Queries)

Instance NameSpace

VB.NET
Imports System.Data 
Imports System.Data.SqlClient 


ASP.NET & System.Data.SqlClient

การสร้างตาราง

USE [mydatabase]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[files](
[FilesID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[FilesName] [image] NULL,
[FilesType] [varchar](20) NULL,
CONSTRAINT [PK_files] PRIMARY KEY CLUSTERED 
(
[FilesID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF


แก้ชื่อฐานข้อมูลตรง USE [mydatabase] ให้ถูกต้องแล้วทำการ Execute เพื่อสร้างฐานข้อมูล

เริ่มต้นด้วยการสร้าง Project ใหม่บน Visual Studio เลือก Application เป็น ASP.NET Web Site

ASP.NET SQL Server BLOB Binary Data

ตั้งชื่อ Project เป็น ASPNetBLOB เลือกภาษาที่ต้องการ สามารถใช้ได้กับ .NET Framework ทุกเวอร์ชั่น

สร้างไฟล์และ Code ทั้งหมดตามในตัวอย่าง

Language Code : VB.NET || C#

Default.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <input id="btnReset" type="reset" value="Reset" /></div>
       </asp:Panel>
    
    </form>
</body>
</html>


Default.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Me.pnlForm.Visible = False

        If Me.fUpload.HasFile = False Or Me.txtName.Text = "" Then
            Me.lblStatus.Text = "Please input Name and Chooes File."
        Else

            '*** Read Binary Data ***'
            Dim imbByte(fUpload.PostedFile.InputStream.Length) As Byte
            fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length)

            '*** MimeType ***'
            Dim ExtType As String = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower()
            Dim strMIME As String = Nothing
            Select Case ExtType
                Case ".gif"
                    strMIME = "image/gif"
                Case ".jpg", ".jpeg", ".jpe"
                    strMIME = "image/jpeg"
                Case ".png"
                    strMIME = "image/png"
                Case Else
                    Me.lblStatus.Text = "Invalid file type."
                    Exit Sub
            End Select

            '*** Insert to Database ***'
            Dim objConn As New SqlConnection
            Dim strConnString, strSQL As String

            strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"

            strSQL = "INSERT INTO files (Name,FilesName,FilesType) " & _
            " VALUES " & _
            " (@sName,@sFilesName,@sFilesType)"
            objConn.ConnectionString = strConnString
            objConn.Open()

            Dim objCmd As New SqlCommand(strSQL, objConn)
            objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = Me.txtName.Text
            objCmd.Parameters.Add("@sFilesName", SqlDbType.Binary).Value = imbByte
            objCmd.Parameters.Add("@sFilesType", SqlDbType.VarChar).Value = strMIME
            objCmd.ExecuteNonQuery()

            objConn.Close()
            objConn = Nothing

            Me.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
        End If
    End Sub

End Class


Edit.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Edit.aspx.vb" Inherits="Edit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
<form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Image ID="ImgPic" runat="server" />
            <br />
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <input id="btnReset" type="reset" value="Reset" />
            <asp:Button ID="btnDel" runat="server" Text="Delete" />            
       </asp:Panel>
    </div>
    </form>
</body>
</html>









Edit.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class Edit
    Inherits System.Web.UI.Page

    Dim objConn As New SqlConnection
    Dim objCmd As SqlCommand
    Dim strConnString, strSQL As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.btnDel.Attributes.Add("OnClick", "return confirm('Are you sure delete?');")

        strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()

        If Not Page.IsPostBack() Then
            ViewData()
        End If
    End Sub

    Protected Sub ViewData()
        '*** DataTable ***'
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New DataTable
        strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID "
        dtAdapter = New SqlDataAdapter(strSQL, objConn)
        objCmd = dtAdapter.SelectCommand
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        dtAdapter.Fill(dt)

        If dt.Rows.Count > 0 Then
            Me.ImgPic.ImageUrl = "ViewImg.aspx?FilesID=" & dt.Rows(0)("FilesID")
            Me.txtName.Text = dt.Rows(0)("Name")
        End If

        dt = Nothing
    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Me.pnlForm.Visible = False

        If Me.txtName.Text = "" Then
            Me.lblStatus.Text = "Please input Name."
        Else

            '*** Update Name ***'
            strSQL = "UPDATE files SET Name = @sName " & _
                   " WHERE FilesID = @sFilesID "

            objCmd = New SqlCommand(strSQL, objConn)
            objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = Me.txtName.Text
            objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
            objCmd.ExecuteNonQuery()

            '*** Update Picture ***'
            If Me.fUpload.HasFile = True Then
                '*** Read Binary Data ***'
                Dim imbByte(fUpload.PostedFile.InputStream.Length) As Byte
                fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length)

                '*** MimeType ***'
                Dim ExtType As String = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower()
                Dim strMIME As String = Nothing
                Select Case ExtType
                    Case ".gif"
                        strMIME = "image/gif"
                    Case ".jpg", ".jpeg", ".jpe"
                        strMIME = "image/jpeg"
                    Case ".png"
                        strMIME = "image/png"
                    Case Else
                        Me.lblStatus.Text = "Invalid file type."
                        Exit Sub
                End Select

                strSQL = "UPDATE files SET FilesName = @sFilesName , FilesType = @sFilesType  " & _
                       " WHERE FilesID = @sFilesID "

                objCmd = New SqlCommand(strSQL, objConn)
                objCmd.Parameters.Add("@sFilesName", SqlDbType.Binary).Value = imbByte
                objCmd.Parameters.Add("@sFilesType", SqlDbType.VarChar).Value = strMIME
                objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
                objCmd.ExecuteNonQuery()

            End If

            Me.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
        End If
    End Sub

    Protected Sub btnDel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDel.Click
        Me.pnlForm.Visible = False
        '*** Delete Rows ***'
        strSQL = "DELETE FROM files  " & _
               " WHERE FilesID = @sFilesID "

        objCmd = New SqlCommand(strSQL, objConn)
        objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = Me.txtName.Text
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        objCmd.ExecuteNonQuery()
        Me.lblStatus.Text = "Delete Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

End Class


ListPicture.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ListPicture.aspx.vb" Inherits="ListPicture" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
 <asp:GridView id="myGridView" runat="server" AutoGenerateColumns="False">
	<Columns>
	<asp:TemplateField HeaderText="ID">
		<ItemTemplate>
			<asp:Label id="lblFilesID" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Name">
		<ItemTemplate>
			<asp:Label id="lblName" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Picture">
		<ItemTemplate>
			<asp:Image ID="ImgPic" runat="server" />
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Edit">
		<ItemTemplate>
            <asp:HyperLink ID="hplEdit" runat="server">Edit</asp:HyperLink>
        </ItemTemplate>
	</asp:TemplateField>

	</Columns>
</asp:GridView>
    
    </div>
    </form>
</body>
</html>


ListPicture.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class ListPicture
    Inherits System.Web.UI.Page

    Dim objConn As SqlConnection
    Dim objCmd As SqlCommand

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strConnString As String
        strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn = New SqlConnection(strConnString)
        objConn.Open()

        BindData()
    End Sub

    Protected Sub BindData()
        Dim strSQL As String
        strSQL = "SELECT * FROM files ORDER BY FilesID ASC"

        Dim dtReader As SqlDataReader
        objCmd = New SqlCommand(strSQL, objConn)
        dtReader = objCmd.ExecuteReader()

        '*** BindData to GridView ***'
        myGridView.DataSource = dtReader
        myGridView.DataBind()

        dtReader.Close()
        dtReader = Nothing
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

    Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
        '*** FilesID ***'
        Dim lblFilesID As Label = DirectCast(e.Row.FindControl("lblFilesID"), Label)
        If Not IsNothing(lblFilesID) Then
            lblFilesID.Text = e.Row.DataItem("FilesID")
        End If

        '*** Name ***'
        Dim lblName As Label = DirectCast(e.Row.FindControl("lblName"), Label)
        If Not IsNothing(lblName) Then
            lblName.Text = e.Row.DataItem("Name")
        End If

        '*** Picture ***'
        Dim ImgPic As Image = DirectCast(e.Row.FindControl("ImgPic"), Image)
        If Not IsNothing(ImgPic) Then
            ImgPic.ImageUrl = "ViewImg.aspx?FilesID= " & e.Row.DataItem("FilesID")
        End If

        '*** Hyperlink ***'
        Dim hplEdit As HyperLink = DirectCast(e.Row.FindControl("hplEdit"), HyperLink)
        If Not IsNothing(hplEdit) Then
            hplEdit.Text = "Edit"
            hplEdit.NavigateUrl = "Edit.aspx?FilesID=" & e.Row.DataItem("FilesID")
        End If

    End Sub

End Class


ViewImg.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ViewImg.aspx.vb" Inherits="ViewImg" %>


ViewImg.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class ViewImg
    Inherits System.Web.UI.Page

    Dim objConn As New SqlConnection
    Dim objCmd As SqlCommand
    Dim strConnString, strSQL As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()

        '*** DataTable ***'
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New DataTable
        strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID "
        dtAdapter = New SqlDataAdapter(strSQL, objConn)
        objCmd = dtAdapter.SelectCommand
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        dtAdapter.Fill(dt)

        If dt.Rows.Count > 0 Then
            Response.ContentType = dt.Rows(0)("FilesType").ToString()
            Response.BinaryWrite(dt.Rows(0)("FilesName"))
        End If

        dt = Nothing
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

End Class









Screenshot

ASP.NET SQL Server BLOB Binary Data

Screen หน้าจอสำหรับอัพโหลด (Upload Binary) ข้อมูลลงใน BLOB


ASP.NET SQL Server BLOB Binary Data

Screen หน้าจอสำหรับแสดงข้อมูล (View BLOB)


ASP.NET SQL Server BLOB Binary Data

Screen หน้าจอสำหรับแก้ไขข้อมูล (Edit BLOB)


ASP.NET SQL Server BLOB Binary Data

Screen หน้าจอสำหรับการลบข้อมูล (Delete BLOB)



ASP.NET System.Data.SqlClient - Parameter Query


ASP.NET & System.Data.SqlClient


   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2011-06-02 14:23:54 / 2017-03-29 10:33:47
  Download : Download  ASP.NET SQL Server BLOB Binary Data and Parameterized Query
 Sponsored Links / Related

 
ASP.NET SQL Server Connect to Database
Rating :

 
ASP.NET SQL Server List Table Properties
Rating :

 
ASP.NET SQL Server List Record
Rating :

 
ASP.NET SQL Server & OleDb (System.Data.OleDb)
Rating :

 
ASP.NET SQL Server & Odbc (System.Data.Odbc)
Rating :

 
ASP.NET SQL Server Random Record
Rating :

 
ASP.NET SQL Server List Record Paging/Pagination
Rating :

 
ASP.NET SQL Server Search Record
Rating :

 
ASP.NET SQL Server Search Record Paging/Pagination
Rating :

 
ASP.NET SQL Server Add/Insert Record
Rating :

 
ASP.NET SQL Server Add-Insert Multiple Record
Rating :

 
ASP.NET SQL Server Check Already Exists Add/Insert Record
Rating :

 
ASP.NET SQL Server Transaction (BeginTransaction,Commit,Rollback)
Rating :

 
ASP.NET SQL Server Edit/Update Record
Rating :

 
ASP.NET SQL Server Delete Record
Rating :

 
ASP.NET SQL Server Multiple Checkbox Delete Record
Rating :

 
ASP.NET SQL Server and GridView, DataSource
Rating :

 
ASP.NET SQL Server Database Class
Rating :

 
ASP.NET SQL Server Database Class (Visual Studio .Net 2003 - .NET 1.1)
Rating :

 
ASP.NET SQL Server Database Class (Visual Studio 2005,2008,2010 - .NET 2.0,3.5,4.0)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่