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

Registered : 107,651

HOME > ASP.NET > ASP.NET Microsoft SQL Server (System.Data.SqlClient) > ASP.NET SQL Server Database Class





Clound SSD Virtual Server

ASP.NET SQL Server Database Class

ASP.NET SQL Server Database Class ตัวอย่างนี้ผมได้ออกแบบ Database Class ไว้สำหรับการจัดการกับฐานข้อมูล ASP กับ SQL Server โดยใช้ NameSpace ของ System.Data.SqlClient ซึ่งมีฟังก์ชั่นครบในการใช้งานครับ ไม่ว่าจะเป็นการ เพิ่ม/ลบ/แก้ไข/อ่าน สำหรับตัวอย่างนี้ผมเขียนบน Framework 2.0,Framework 3.5 ครับ

Instance NameSpace

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


ASP.NET & System.Data.SqlClient

Language Code : VB.NET || C#

Web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"/>
</appSettings>
</configuration>



App_Code/clsDatabase.vb

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class clsDatabase
    Private objConn As SqlConnection
    Private objCmd As SqlCommand
    Private Trans As SqlTransaction
    Private strConnString As String

    Public Sub New()
        strConnString = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
    End Sub

    Public Function QueryDataReader(ByVal strSQL As String) As SqlDataReader
        Dim dtReader As SqlDataReader
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        objCmd = New SqlCommand(strSQL, objConn)
        dtReader = objCmd.ExecuteReader()
        Return dtReader '*** Return DataReader ***'
    End Function

    Public Function QueryDataSet(ByVal strSQL As String) As DataSet
        Dim ds As New DataSet
        Dim dtAdapter As New SqlDataAdapter
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        objCmd = New SqlCommand
        With objCmd
            .Connection = objConn
            .CommandText = strSQL
            .CommandType = CommandType.Text
        End With
        dtAdapter.SelectCommand = objCmd
        dtAdapter.Fill(ds)
        Return ds '*** Return DataSet ***'
    End Function

    Public Function QueryDataTable(ByVal strSQL As String) As DataTable
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New DataTable
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        dtAdapter = New SqlDataAdapter(strSQL, objConn)
        dtAdapter.Fill(dt)
        Return dt '*** Return DataTable ***'
    End Function

    Public Function QueryExecuteNonQuery(ByVal strSQL As String) As Boolean
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        Try
            objCmd = New SqlCommand
            With objCmd
                .Connection = objConn
                .CommandType = CommandType.Text
                .CommandText = strSQL
            End With
            objCmd.ExecuteNonQuery()
            Return True '*** Return True ***'
        Catch ex As Exception
            Return False '*** Return False ***'
        End Try
    End Function

    Public Function QueryExecuteScalar(ByVal strSQL As String) As Object
        Dim obj As Object
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        Try
            objCmd = New SqlCommand
            With objCmd
                .Connection = objConn
                .CommandType = CommandType.Text
                .CommandText = strSQL
            End With
            obj = objCmd.ExecuteScalar() '*** Return Scalar ***'
            Return obj
        Catch ex As Exception
            Return Nothing '*** Return Nothing ***'
        End Try
    End Function

    Public Function TransStart()
        objConn = New SqlConnection
        With objConn
            .ConnectionString = strConnString
            .Open()
        End With
        Trans = objConn.BeginTransaction(IsolationLevel.ReadCommitted)
    End Function

    Public Function TransExecute(ByVal strSQL As String) As Boolean
        objCmd = New SqlCommand
        With objCmd
            .Connection = objConn
            .Transaction = Trans
            .CommandType = CommandType.Text
            .CommandText = strSQL
        End With
        objCmd.ExecuteNonQuery()
    End Function

    Public Function TransRollBack()
        Trans.Rollback()
    End Function

    Public Function TransCommit()
        Trans.Commit()
    End Function

    Public Sub Close()
        objConn.Close()
        objConn = Nothing
    End Sub

End Class









AspNetDatabase.aspx

<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<%@ Page Language="VB" %>

<script runat="server">
	
	Dim clsDB As New clsDatabase
    Sub Page_Load(sender As Object, e As EventArgs)	
        Call myDataReader()
        Call myDataSet()
        Call myDataTable()
        Call myQueryExecuteScalar()
        Call myExecuteNonQuery()
        Call myExecuteTransaction()	
	End Sub


    '*** DataReader ***'
    Sub myDataReader()
        Dim strSQL As String
        Dim dtReader As SqlDataReader
        strSQL = "SELECT * FROM customer "
        dtReader = clsDB.QueryDataReader(strSQL)
        Me.myDataGrid1.DataSource = dtReader
        Me.myDataGrid1.DataBind()

        '*** Bind Rows ***'
        'If dtReader.HasRows = True Then
        '    Me.lblCustomerID.Text = dtReader.Item("CustomerID")
        '    Me.lblName.Text = dtReader.Item("Name")
        '    Me.lblEmail.Text = dtReader.Item("Email")
        '    Me.lblCountryCode.Text = dtReader.Item("CountryCode")
        '    Me.lblBudget.Text = dtReader.Item("Budget")
        '    Me.lblUsed.Text = dtReader.Item("Used")
        'End If
        clsDB.Close()
    End Sub

    '*** DataSet ***'
    Sub myDataSet()
        Dim strSQL As String
        Dim ds As DataSet
        strSQL = "SELECT * FROM customer "
        ds = clsDB.QueryDataSet(strSQL)
        Me.myDataGrid2.DataSource = ds.Tables(0).DefaultView
        Me.myDataGrid2.DataBind()

        '*** Bind Rows ***'
        'If ds.Tables(0).Rows.Count > 0 Then
        '    Me.lblCustomerID.Text = ds.Tables(0).Rows(0)("CustomerID")
        '    Me.lblName.Text = ds.Tables(0).Rows(0)("Name")
        '    Me.lblEmail.Text = ds.Tables(0).Rows(0)("Email")
        '    Me.lblCountryCode.Text = ds.Tables(0).Rows(0)("CountryCode")
        '    Me.lblBudget.Text = ds.Tables(0).Rows(0)("Budget")
        '    Me.lblUsed.Text = ds.Tables(0).Rows(0)("Used")
        'End If
        clsDB.Close()
    End Sub

    '*** DataTable ***'
    Sub myDataTable()
        Dim strSQL As String
        Dim dt As DataTable
        strSQL = "SELECT * FROM customer "
        dt = clsDB.QueryDataTable(strSQL)
        Me.myDataGrid3.DataSource = dt
        Me.myDataGrid3.DataBind()

        '*** Bind Rows ***'
        If dt.Rows.Count > 0 Then
            Me.lblCustomerID.Text = dt.Rows(0)("CustomerID")
            Me.lblName.Text = dt.Rows(0)("Name")
            Me.lblEmail.Text = dt.Rows(0)("Email")
            Me.lblCountryCode.Text = dt.Rows(0)("CountryCode")
            Me.lblBudget.Text = dt.Rows(0)("Budget")
            Me.lblUsed.Text = dt.Rows(0)("Used")
        End If
        clsDB.Close()
    End Sub

    '*** Execute Scalar ***'
    Sub myQueryExecuteScalar()
        Dim strSQL As String
        strSQL = "SELECT MAX(Budget) FROM customer "
        Me.lblText.Text = clsDB.QueryExecuteScalar(strSQL)
        clsDB.Close()
    End Sub

    '*** ExecuteNonQuery ***'
    Sub myExecuteNonQuery()
        Dim strSQL1, strSQL2, strSQL3 As String

        '*** Insert ***'
        strSQL1 = "INSERT INTO customer (CustomerID,Name,Email,CountryCode,Budget,Used) " & _
        " VALUES('C005','Weerachai Nukitram','[email protected]','TH','200000','100000')"
        If clsDB.QueryExecuteNonQuery(strSQL1) = True Then
            '*** Condition Success ***'
        Else
            '*** Condition Error ***'
        End If
        clsDB.Close()

        '*** Update ***'
        strSQL2 = "UPDATE customer SET Budget = '3000000' WHERE CustomerID = 'C005' "
        If clsDB.QueryExecuteNonQuery(strSQL2) = True Then
            '*** Condition Success ***'
        Else
            '*** Condition Error ***'
        End If
        clsDB.Close()

        '*** Delete ***'
        strSQL3 = "DELETE FROM customer WHERE CustomerID = 'C005' "
        If clsDB.QueryExecuteNonQuery(strSQL3) = True Then
            '*** Condition Success ***'
        Else
            '*** Condition Error ***'
        End If
        clsDB.Close()
    End Sub

    '*** Execute Transaction ***'
    Sub myExecuteTransaction()
        Dim strSQL1, strSQL2, strSQL3 As String

        '*** Start Transaction ***'
        clsDB.TransStart()

        Try
            '*** Insert ***'
            strSQL1 = "INSERT INTO customer (CustomerID,Name,Email,CountryCode,Budget,Used) " & _
            " VALUES('C005','Weerachai Nukitram','[email protected]','TH','200000','100000')"
            clsDB.TransExecute(strSQL1) '*** Execute Query 1 ***'

            '*** Update ***'
            strSQL2 = "UPDATE customer SET Budget = '3000000' WHERE CustomerID = 'C005' "
            clsDB.TransExecute(strSQL2) '*** Execute Query 2 ***

            '*** Delete ***'
            strSQL3 = "DELETE FROM customer WHERE CustomerID = 'C005' "
            clsDB.TransExecute(strSQL3) '*** Execute Query 3 ***

            '*** Commit Transaction ***'
            clsDB.TransCommit()

        Catch ex As Exception
            '*** RollBack Transaction ***'
            clsDB.TransRollBack()
        End Try
        clsDB.Close()
    End Sub

</script>
<html>
<head>
<title>ThaiCreate.Com ASP.NET - Database Class</title>
</head>
<body>
	<form id="form1" runat="server">
			<asp:DataGrid id="myDataGrid1" runat="server"></asp:DataGrid>
			<br>
			<br>
			<asp:DataGrid id="myDataGrid2" runat="server"></asp:DataGrid><br>
			<br>
			<asp:DataGrid id="myDataGrid3" runat="server"></asp:DataGrid><br>
			<table style="WIDTH: 300px" border="1">
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderCustomerID" runat="server" Text="CustomerID"></asp:Label></td>
					<td style="WIDTH: 213px">
						<asp:Label id="lblCustomerID" runat="server"></asp:Label></td>
				</tr>
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderName" runat="server" Text="Name"></asp:Label></td>
					<td style="WIDTH: 213px">
						<asp:Label id="lblName" runat="server"></asp:Label></td>
				</tr>
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderEmail" runat="server" Text="Email"></asp:Label></td>
					<td style="WIDTH: 213px; HEIGHT: 23px">
						<asp:Label id="lblEmail" runat="server"></asp:Label></td>
				</tr>
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderCountryCode" runat="server" Text="CountryCode"></asp:Label></td>
					<td style="WIDTH: 213px; HEIGHT: 23px">
						<asp:Label id="lblCountryCode" runat="server"></asp:Label></td>
				</tr>
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderBudget" runat="server" Text="Budget"></asp:Label></td>
					<td style="WIDTH: 213px; HEIGHT: 21px">
						<asp:Label id="lblBudget" runat="server"></asp:Label></td>
				</tr>
				<tr>
					<td style="WIDTH: 93px">
						<asp:Label id="lblHeaderUsed" runat="server" Text="Used"></asp:Label></td>
					<td style="WIDTH: 213px; HEIGHT: 21px">
						<asp:Label id="lblUsed" runat="server"></asp:Label></td>
				</tr>
			</table>
			<br>
			<asp:Label id="lblText" runat="server"></asp:Label>
	</form>
</body>
</html>




ASP.NET System.Data.SqlClient - Parameter Query









   
Share


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


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


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2008-12-06 13:34:22 / 2017-03-29 10:32:09
  Download : Download  ASP.NET SQL Server Database Class
 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 (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 :

 
ASP.NET SQL Server BLOB Binary Data and Parameterized Query
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
ปรับแต่งเว็บให้โหลดเร็ว


สุดยอด Source Code V2.0
 

แจ้งชำระเงิน/โอนเงิน
 

Hit Link
   







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