 |
|
|
 |
 |
|
Code (C#)
// New class ขึ้นมาชื่ออะไรก็ได้ ในตัวอย่าง เป็น AppDataLayer.cs ค่ะ
using System.Data.SqlClient ;
using System.Configuration ;
namespace AppDataLayer
{
public class AppConnectorHelper
{
// เป็นตัวแปรเก็บ connectionString จะอ่านจาก Txt file หรือ Web.Config
// ยังไงก็ได้ ขอให้ถูก Syntax ก็พอ Code นี้ใช้ได้ทั้ง Web app และ Win App ค่ะ
public static string ConnectionString = string.Empty;
public static int DefaultCommandTimeOut = 500 ;
// flag กำหนดให้ throw error หรือ แค่ return ค่า false ถ้า เกิด error ค่ะ
public static bool RaiseErrorForDebugChecked = false ;
//nTimeOut เป็นเวลา timeout ของการ Execute กำหนดในกรณีที่ต้องใช้เวลานาน
public static bool ExecuteSQLCommand ( string strSQLCommand ,int nTimeOut
,SqlParameterCollection Params )
{
SqlConnection aConn = new SqlConnection (ConnectionString ) ;
SqlCommand aCommand = new SqlCommand (aConn ,strCommand) ;
aCommand.CommandTimeOut = nTimeOut ;
bool result = false ;
if ((Params != null)&&(Params.Count >0) )
{
foreach ( SqlParamater iParam in Params)
aCommand.Parameters.Add(iParam) ;
}
try
{
aConn.Open() ; // เปิดการเชื่อมต่อ
aCommand.ExecuteNonQuery() ; // Execute command
result = true ;
}
catch ( Exception ex)
{
result = false ;
if ( AppConnectorHelper.RaiseErrorForDebugChecked )
throw new Exception ( ex.message ) ;
}
finally
{
if(aConn != null) aConn.Close() ;
}
return result ;
}
// Overload เพื่อให้เขียนง่ายและสั้นค่ะ
public static bool ExecuteSQLCommand ( string strSQLCommand ,SqlParameterCollection Params )
{
return ExecuteSQLCommand ( strSQLCommand ,AppConnectorHelper.DefaultCommandTimeOut ,Params ) ;
}
public static bool ExecuteSQLCommand ( string strSQLCommand )
{
return ExecuteSQLCommand ( strSQLCommand ,AppConnectorHelper.DefaultCommandTimeOut ,null) ;
}
public static DataTable GetDataTableFromSQLCommand ( string strSQLCommand ,int nTimeOut ,SqlParameterCollection Params )
{
SqlConnection aConn = new SqlConnection (ConnectionString ) ;
SqlDataAdaptor aDataAdaptor = new SqlDataAdaptor () ;
SqlCommand aCommand = new SqlCommand (aConn ,strCommand) ;
aCommand.CommandTimeOut = nTimeOut ;
DataTable resultTable = null ;
if ((Params != null)&&(Params.Count >0) )
{
foreach ( SqlParamater iParam in Params)
aCommand.Parameters.Add(iParam) ;
}
aDataAdaptor.SelectCommand = aCommand ;
try
{
resultTable = new DataTable();
aConn.Open() ; // เปิดการเชื่อมต่อ
aDataAdaptor.Fill( resultTable ) ;
}
catch ( Exception ex)
{
resultTable = null ;
if ( AppConnectorHelper.RaiseErrorForDebugChecked )
throw new Exception ( ex.message ) ;
}
finally
{
if(aConn != null) aConn.Close() ;
}
return resultTable ;
}
// Overload
public static DataTable GetDataTableFromSQLCommand ( string strSQLCommand ,SqlParameterCollection Params )
{
return GetDataTableFromSQLCommand ( strSQLCommand ,AppConnectorHelper.DefaultCommandTimeOut ,Params );
}
public static DataTable GetDataTableFromSQLCommand ( string strSQLCommand )
{
return GetDataTableFromSQLCommand ( strSQLCommand ,AppConnectorHelper.DefaultCommandTimeOut ,null);
}
// ส่วน method Get DataSet ,ExecuteScalar หรือ ExecuteReader ลองไปเขียนนะคะ
}
}
......
......
// ใน Code behide หรือ Code Page
using System.Data.SqlClient ;
using AppDataLayer ; // << แจ้งขอใช้ Namespace ที่เราเขียน
void Page_Load()
{
if (!isPostBack)
{
// กำหนด connection string ของเรา
AppConnectorHelper.ConnectionString = ..... ; // จะย้ายไปอยู่ที่ Global.asax จะดีกว่าเพราะทำแคครั้งเดียวค่ะ
// ตัวอย่างการใช้
// สมมุติมี Grid ชื่อ GrdProduct นะคะ
string strGetAllProductCommand = "SELECT * FROM PRODUCT" ;
GrdProduct.DataSource = AppDataHelper.GetDataTable( strGetAllProductCommand ) ;
//หรือ
SqlParameterCollection CommandParam = new SqlParameterCollection () ;
// วันที่ 1 ของเดือนนี้
DateTime MonthStart = new DateTime( DateTime.now.year ,DateTime.now.month ,1);
// วันสุดท้ายของเดือนนี้ ซึ่งอาจจะเป็น 30 ,31 หรือ 28
// บวกเพิ่มไปหนึ่งเดือน จะเป็นที่ 1 ของเดือนถัดไป จากนั้น ลบ 1 วัน จะได้วันสุดท้ายของเดือนนี้
DateTime MonthEnd = MonthStart.AddMonths(1).AddDays(-1);
CommandParam.AddWithValue("@VAR_BEGIN_DATE" ,MonthStart ) ;
CommandParam.AddWithValue("@VAR_END_DATE" ,MonthEnd ) ;
string strGetSomeProductCommand = "SELECT * FROM [PRODUCT] "
+ " WHERE [ORDER_DATE] BETWEEN @VAR_BEGIN_DATE AND @VAR_END_DATE " ;
GrdProduct.DataSource = AppDataHelper.GetDataTable(strGetSomeProductCommand ,CommandParam) ;
// ตัวอย่าง การ Execute
string InsertCommand = "INSERT INTO [PRODUCT] VALUES (@VAR_DESCRIPTION ,@VAR_ORDER_DATE)" ;
string NewNameStr = "ABC's for kids" ;
SqlParameterCollection CommandParam = new SqlParameterCollection () ;
CommandParam.AddWithValue("@VAR_DESCRIPTION" ,NewNameStr) ;
CommandParam.AddWithValue("@VAR_ORDER_DATE" ,DateTime.now) ;
AppDataHelper.ExecuteSQLCommand ( InsertCommand ,CommandParam);
// หรือ
string DeleteCommand = "DELETE FROM [PRODUCT] "
+ " WHERE ([Order_date] <= @VAR_DELTED_DATE)" ;
SqlParameterCollection CommandParam = new SqlParameterCollection () ;
CommandParam.AddWithValue("@VAR_DELTED_DATE" ,DateTime.now) ;
AppDataHelper.ExecuteSQLCommand ( DeleteCommand ,CommandParam);
// ถ้าใช้ SQL Parameter จะช่วยลดความซับซ้อนตอน declare SQL Command ได้มาก
// ลดโอกาสผิดพลาดจากอักขระพิเศษ ' " ได้ทั้งหมด และป้องกันการใช้ SQL Injection ด้วยค่ะ
}
}
|
 |
 |
 |
 |
Date :
2010-02-12 18:28:13 |
By :
blurEye |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (VB.NET)
Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration
Public Class clsDatabase
Private objConn As OleDbConnection
Private objCmd As OleDbCommand
Private Trans As OleDbTransaction
Private strConnString As String
Public Sub New()
strConnString = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
End Sub
Public Function QueryDataReader(ByVal strSQL As String) As OleDbDataReader
Dim dtReader As OleDbDataReader
objConn = New OleDbConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
objCmd = New OleDbCommand(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 OleDbDataAdapter
objConn = New OleDbConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
objCmd = New OleDbCommand
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 OleDbDataAdapter
Dim dt As New DataTable
objConn = New OleDbConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
dtAdapter = New OleDbDataAdapter(strSQL, objConn)
dtAdapter.Fill(dt)
Return dt '*** Return DataTable ***'
End Function
Public Function QueryExecuteNonQuery(ByVal strSQL As String) As Boolean
objConn = New OleDbConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
Try
objCmd = New OleDbCommand
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 OleDbConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
Try
objCmd = New OleDbCommand
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 OleDbConnection
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 OleDbCommand
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
ASP.NET Microsoft Access Database Class
|
 |
 |
 |
 |
Date :
2010-02-12 18:47:56 |
By :
webmaster |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
อ้าว เก๋ มีคนมาตอบให้แล้วนี่นา อิอิ
|
 |
 |
 |
 |
Date :
2010-02-14 14:21:11 |
By :
somooo |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ขอบคุณค่ะ จะลองทำดูนะคะ
|
 |
 |
 |
 |
Date :
2010-02-15 09:47:51 |
By :
njnight |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ขอบคุณมากๆ นะคะ ทำได้แล้ว
ปวดหัวอยู่ตั้งนาน
|
 |
 |
 |
 |
Date :
2010-02-15 11:03:22 |
By :
njnight |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|