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,038

HOME > .NET Framework > Forum > มาดู SqlDatabaseManager New Version ก่อนเอาไปลงไว้ใน Community


 

[.NET] มาดู SqlDatabaseManager New Version ก่อนเอาไปลงไว้ใน Community

 
Topic : 041353



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์



มี version ใหม่แล้วนะ แต่ยังไม่ได้เอาไป update ใน community (เพราะโรคเดิมๆ อู้ไม่เลิก)

มีอะไรใน vision ใหม่

- สามารถใช้ transaction ได้
- add parameter โดยไม่ต้อง กำหนด SqlDataType
- add parameter ได้ทุก type โดยต้องกำหนด type ให้ตรงกับใน Sql Server (สามารถเทียบระหว่าง .Net Type กับ Sql Type ได้จาก Mapping CLR Parameter Data)
- เรียก connection string จาก web.config ด้วย keyname ได้
- เมื่อ command success สามารถบอกจำนวนของ row ที่ทำการ insert update delete ได้
- ยกเลิก method AddBinaryStream() โดยเปลี่ยนไปใช้ SqlConvert class แทน
- สามารถกำหนด format ของ datetime type ตามความต้องการได้ (ด้วย SqlConvert class)
- ลดลูปในการทำงาน ทำให้ทำงานเร็วขึ้น
- คืน memmory เมื่อเสร็จสิ้นการทำงาน

SqlDatabaseManager Class

#Constructor
- public SqlDatabaseManager() จะใช้ค่า Connection ที่ Config ไว้ที่ Web.Config โดยเรียกจาก KeyName ที่ชื่อว่า SqlConnectionString
- public SqlDatabaseManager(string SqlConnectionKeyName) จะใช้ค่า Connection ที่ Config ไว้ที่ Web.Config โดยเรียกจาก KeyName ที่กำหนดเอง
- public SqlDatabaseManager(string SqlConnectionKeyName, string SqlConnectionString) กำหนดค่า KeyName และ Connection String เอง

#Property
- public virtual string ConnectionKeyName กำหนดและเรียกดูค่า Connection KeyName
- public virtual string ConnectionString กำหนดและเรียกดูค่า Connection String
- public virtual string CommandString กำหนดและเรียกดูค่า Sql Command String
- public virtual bool IsSuccess เรียกดูผลของ Sql Command
- public virtual string Message เรียกดูคำอธิบายผลของ Sql Command
- public virtual int RowsAffected เรียกดูจำนวน Row ที่ทำการ ExecuteNonQuery ไป

#Method
- public virtual void AddParameter(string ParameterName, object ParameterValue) กำหนดชื่อ parameter และป้อน value เพื่อแทนค่าใน Sql Command
- public virtual void TransactionStart() เริ่มต้นการใช้งาน Transaction
- public virtual bool ExecuteTransaction() คำสั่งสำหรับรัน Transaction
- public virtual DataTable ExecuteQuery() คำสั่งรัน Query Command
- public virtual object ExecuteScalar() คำสั่งรัน Query Command แบบ Scalar
- public virtual bool ExecuteNonQuery() คำสั่งรัน Command แบบไม่มีการ Return ค่ากลับมา

SqlConvert Class Class ที่ต้องใช้งานร่วมกัน

#Method
- public static byte[] ToVarBinary(Stream BinaryStream, int StreamLength) แปลง BanaryStream (จาก FileUpload Control) เป็น byte[] เพื่อเก็บลง Sql Server
- public static DateTime ToDateTime(string DateString) แปลง String เป็น DateTime Type ที่มี Format 'd/M/yyyy'
- public static DateTime ToDateTime(string DateString, string DateFormat) แปลง String เป็น DateTime Type ที่มี Format ที่กำหนดเอง



Tag : - - - -

Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2010-04-07 11:58:48 By : tungman View : 1694 Reply : 8
 

 

No. 1



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


Basic Query แบบบ้านๆ

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestSqlConnection.aspx.cs" Inherits="TestSqlConnection" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
13.        <br />
14.        <br />
15.        <asp:GridView ID="GridView1" runat="server">
16.        </asp:GridView>
17.    </div>
18.    </form>
19.</body>
20.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.using System.Data;
09. 
10.public partial class TestSqlConnection : System.Web.UI.Page
11.{
12.    protected void Page_Load(object sender, EventArgs e)
13.    {
14.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
15.        SqlDatabaseManager1.CommandString = "Select [DayID], [DayName] From [DayTable]";
16. 
17.        DataTable Dt = new DataTable();
18.        Dt = SqlDatabaseManager1.ExecuteQuery();
19. 
20.        GridView1.DataSource = Dt;
21.        GridView1.DataBind();
22. 
23.        Label1.Text = SqlDatabaseManager1.Message;
24.    }
25.}


ผลลัพธ์
1
Date : 2010-04-07 11:59:21 By : tungman
 

 

No. 2



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


Query แบบมีเงื่อนไขนิดๆ

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestSqlConnection.aspx.cs" Inherits="TestSqlConnection" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
13.        <br />
14.        <br />
15.        <asp:GridView ID="GridView1" runat="server">
16.        </asp:GridView>
17.    </div>
18.    </form>
19.</body>
20.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.using System.Data;
09. 
10.public partial class TestSqlConnection : System.Web.UI.Page
11.{
12.    protected void Page_Load(object sender, EventArgs e)
13.    {
14.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
15.        SqlDatabaseManager1.CommandString = "Select [DayID], [DayName] From [DayTable] Where [DayName] Like @DayName Or [DayID]=@DayID";
16.        SqlDatabaseManager1.AddParameter("@DayName", "Wed%");
17.        SqlDatabaseManager1.AddParameter("@DayID", 2);
18. 
19.        DataTable Dt = new DataTable();
20.        Dt = SqlDatabaseManager1.ExecuteQuery();
21. 
22.        GridView1.DataSource = Dt;
23.        GridView1.DataBind();
24. 
25.        Label1.Text = SqlDatabaseManager1.Message;
26.    }
27.}


ผลลัพธ์
2
Date : 2010-04-07 11:59:50 By : tungman
 

 

No. 3



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


Query โดยใช้ Datetime แบบ String (ใช้ native command 'SmallDateTime()' หรือ 'DateTime()' ช่วย แต่ได้แค่ format เดียวคือ 'd/M/yyyy')

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestSqlConnection.aspx.cs" Inherits="TestSqlConnection" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
13.        <br />
14.        <br />
15.        <asp:GridView ID="GridView1" runat="server">
16.        </asp:GridView>
17.    </div>
18.    </form>
19.</body>
20.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.using System.Data;
09. 
10.public partial class TestSqlConnection : System.Web.UI.Page
11.{
12.    protected void Page_Load(object sender, EventArgs e)
13.    {
14.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
15.        SqlDatabaseManager1.CommandString = "Select [HolidayTable].[HolidayID], [DayTable].[DayName], [HolidayTable].[Holiday], [HolidayTable].[HolidayThaiDetail], [HolidayTable].[HolidayDetail] From [HolidayTable] Inner Join [DayTable] On ([HolidayTable].[DayID] = [DayTable].[DayID]) Where [HolidayTable].[Holiday]=SmallDateTime(@MyDate)";
16.        SqlDatabaseManager1.AddParameter("@MyDate", "13/4/2010");
17. 
18.        DataTable Dt = new DataTable();
19.        Dt = SqlDatabaseManager1.ExecuteQuery();
20. 
21.        GridView1.DataSource = Dt;
22.        GridView1.DataBind();
23. 
24.        Label1.Text = SqlDatabaseManager1.Message;
25.    }
26.}


ผลลัพธ์
3
Date : 2010-04-07 12:00:14 By : tungman
 

 

No. 4



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


Query โดยใช้ Datetime แบบ DateTime Type (แนะนำ)

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestSqlConnection.aspx.cs" Inherits="TestSqlConnection" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
13.        <br />
14.        <br />
15.        <asp:GridView ID="GridView1" runat="server">
16.        </asp:GridView>
17.    </div>
18.    </form>
19.</body>
20.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.using System.Data;
09. 
10.public partial class TestSqlConnection : System.Web.UI.Page
11.{
12.    protected void Page_Load(object sender, EventArgs e)
13.    {
14.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
15.        SqlDatabaseManager1.CommandString = "Select [HolidayTable].[HolidayID], [DayTable].[DayName], [HolidayTable].[Holiday], [HolidayTable].[HolidayThaiDetail], [HolidayTable].[HolidayDetail] From [HolidayTable] Inner Join [DayTable] On ([HolidayTable].[DayID] = [DayTable].[DayID]) Where [HolidayTable].[Holiday]=@MyDate";
16.        SqlDatabaseManager1.AddParameter("@MyDate", SqlConvert.ToDateTime("13/4/2010"));
17. 
18.        DataTable Dt = new DataTable();
19.        Dt = SqlDatabaseManager1.ExecuteQuery();
20. 
21.        GridView1.DataSource = Dt;
22.        GridView1.DataBind();
23. 
24.        Label1.Text = SqlDatabaseManager1.Message;
25.    }
26.}


ผลลัพธ์
3
Date : 2010-04-07 12:00:42 By : tungman
 

 

No. 5



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


การใช้ ExecuteScalar()

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestSqlConnection.aspx.cs" Inherits="TestSqlConnection" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
13.        <br />
14.        <br />
15.        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
16.    </div>
17.    </form>
18.</body>
19.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.public partial class TestSqlConnection : System.Web.UI.Page
09.{
10.    protected void Page_Load(object sender, EventArgs e)
11.    {
12.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
13.        SqlDatabaseManager1.CommandString = "Select Count(*) From [HolidayTable]";
14. 
15.        int AllHoliday = (int)SqlDatabaseManager1.ExecuteScalar();
16. 
17.        Label1.Text = SqlDatabaseManager1.Message;
18.        Label2.Text = "All Holiday in 2010: " + AllHoliday + " Days";
19.    }
20.}


ผลลัพธ์
4
Date : 2010-04-07 12:01:10 By : tungman
 

 

No. 6



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


การใช้งาน ExecuteNonQuery() เพื่อ upload ไฟล์ไปเก็บไว้ใน Sql Server

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFile.aspx.cs" Inherits="UploadFile" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:FileUpload ID="FileUpload1" runat="server" />
13.        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
14.        <asp:Button ID="Button1" runat="server" Text="Button" />
15.        <br />
16.        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
17.        <br />
18.        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
19.    </div>
20.    </form>
21.</body>
22.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.public partial class UploadFile : System.Web.UI.Page
09.{
10.    protected void Page_Load(object sender, EventArgs e)
11.    {
12.        Button1.Click += new EventHandler(Button1_Click);
13.    }
14. 
15.    protected void Button1_Click(object sender, EventArgs e)
16.    {
17.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
18.        SqlDatabaseManager1.CommandString = "Insert Into [UploadFile] ([FileName], [ContentType], [BinaryStream]) Values (@FileName, @ContentType, @BinaryStream)";
19.        SqlDatabaseManager1.AddParameter("@FileName", FileUpload1.PostedFile.FileName);
20.        SqlDatabaseManager1.AddParameter("@ContentType", FileUpload1.PostedFile.ContentType);
21.        SqlDatabaseManager1.AddParameter("@BinaryStream", SqlConvert.ToVarBinary(FileUpload1.PostedFile.InputStream, FileUpload1.PostedFile.ContentLength));
22.        SqlDatabaseManager1.ExecuteNonQuery();
23. 
24.        Label1.Text = SqlDatabaseManager1.Message;
25.        Label2.Text = "Insert " + SqlDatabaseManager1.RowsAffected + " Row(s).";
26.    }
27.}


ผลลัพธ์
5
Date : 2010-04-07 12:01:36 By : tungman
 

 

No. 7



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


การใช้งาน transaction ทำการ upload ไฟล์ไปเก็บไว้ใน Sql Server และเก็บวันที่ upload ไว้อีก table นึง

Code (C#)
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFile.aspx.cs" Inherits="UploadFile" %>
02. 
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04. 
06.<head runat="server">
07.    <title></title>
08.</head>
09.<body>
10.    <form id="form1" runat="server">
11.    <div>
12.        <asp:FileUpload ID="FileUpload1" runat="server" />
13.        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
14.        <asp:Button ID="Button1" runat="server" Text="Button" />
15.        <br />
16.        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
17.        <br />
18.        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
19.        <br />
20.        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
21.        <br />
22.        <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
23.    </div>
24.    </form>
25.</body>
26.</html>

Code (C#)
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07. 
08.using System.Web.Configuration;
09.using System.Data.SqlClient;
10. 
11.public partial class UploadFile : System.Web.UI.Page
12.{
13.    protected void Page_Load(object sender, EventArgs e)
14.    {
15.        Button1.Click += new EventHandler(Button1_Click);
16.    }
17. 
18.    protected void Button1_Click(object sender, EventArgs e)
19.    {
20.        SqlDatabaseManager SqlDatabaseManager1 = new SqlDatabaseManager();
21. 
22.        SqlDatabaseManager1.TransactionStart();
23.        //ตรวจสอบก่อน execute
24.        Label1.Text = SqlDatabaseManager1.Message;
25. 
26.        SqlDatabaseManager1.CommandString = "Insert Into [UploadFile] ([FileName], [ContentType], [BinaryStream]) Values (@FileName, @ContentType, @BinaryStream)";
27.        SqlDatabaseManager1.AddParameter("@FileName", FileUpload1.PostedFile.FileName);
28.        SqlDatabaseManager1.AddParameter("@ContentType", FileUpload1.PostedFile.ContentType);
29.        SqlDatabaseManager1.AddParameter("@BinaryStream", SqlConvert.ToVarBinary(FileUpload1.PostedFile.InputStream, FileUpload1.PostedFile.ContentLength));
30.        SqlDatabaseManager1.ExecuteNonQuery();
31.        //ตรวจสอบตอนรัน command แรก
32.        Label2.Text = SqlDatabaseManager1.Message;
33. 
34.        //สามารถ query ที่ insert ภายใน transaction ได้
35.        SqlDatabaseManager1.CommandString = "Select Max(ID) From [UploadFile]";
36.        int MaxID = (int)SqlDatabaseManager1.ExecuteScalar();
37. 
38.        SqlDatabaseManager1.CommandString = "Insert Into [UploadDetail] ([FileID], [UploadDate]) Value (@FileID, @UploadDate)";
39.        SqlDatabaseManager1.AddParameter("@FileID", MaxID);
40.        SqlDatabaseManager1.AddParameter("@UploadDate", DateTime.Today);
41.        SqlDatabaseManager1.ExecuteNonQuery();
42.        //ตรวจสอบตอนรัน command ที่สาม
43.        Label3.Text = SqlDatabaseManager1.Message;
44. 
45.        SqlDatabaseManager1.ExecuteTransaction();
46.        //ผลของ transaction
47.        Label4.Text = SqlDatabaseManager1.Message;
48.    }
49.}


ผลลัพธ์แบบ error เพราะอยากให้ดูแบบ error เพราะ value ไม่ได้เติม s
6

ผลลัพธ์แบบ success แก้ไข values แล้ว
7
Date : 2010-04-07 12:02:11 By : tungman
 

 

No. 8



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


ส่วน SqlDatabaseManager ให้ไป download ใน community นะครับ

ในบทความเดิมเลยครับ ที่ SqlDatabaseManager

หรือก็อบ source code ด้านล่างไปก็ได้

SqlDatabaseManager.cs
001.using System;
002.using System.Collections.Generic;
003.using System.Linq;
004.using System.Web;
005. 
006.using System.Data;
007.using System.Data.SqlClient;
008.using System.Globalization;
009.using System.IO;
010.using System.Text.RegularExpressions;
011.using System.Web.Configuration;
012. 
013.#region ========== Class SqlDatabaseManager ==========
014./// <summary>
015./// Summary description for SqlDatabase
016./// </summary>
017.public class SqlDatabaseManager
018.{
019.    #region ========== Global Variables ==========
020.    private SqlConnection sqlConnection;
021.    private SqlCommand sqlCommand;
022.    private SqlTransaction sqlTransaction;
023.    private List<string> errorCommand;
024. 
025.    private string sqlConnectionString = string.Empty;
026.    private string sqlConnectionKeyName = string.Empty;
027.    private string sqlCommandString = string.Empty;
028.    private string commandMessage = "You must execute command.";
029.    private bool commandSuccess = false;
030.    private bool transaction = false;
031.    private int rowsAffected = 0;
032.    #endregion
033. 
034.    #region ========= Constructor ==========
035.    /// <summary>
036.    /// Use sql connection string from web.config configulation.
037.    /// </summary>
038.    public SqlDatabaseManager()
039.    {
040.        if (WebConfigurationManager.ConnectionStrings["SqlConnectionString"] != null)
041.        {
042.            //สำหรับ web.config ที่มีการ add connection string ชื่อ SqlConnectionString เอาไว้
043.            //
044.            //ตัวอย่างใน web.config
045.            //<connectionStrings>
046.            //    <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SqlDatabase;Integrated Security=True;" providerName="System.Data.SqlClient"/>
047.            //</connectionStrings>
048. 
049.            sqlConnectionKeyName = "SqlConnectionString";
050.            sqlConnectionString = WebConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();
051.            sqlConnection = new SqlConnection(sqlConnectionString);
052.        }
053.        else
054.        {
055.            sqlConnection = new SqlConnection();       
056.        }
057.    }
058. 
059.    /// <summary>
060.    /// Use sql connection string from web.config configulation by key name.
061.    /// </summary>
062.    public SqlDatabaseManager(string SqlConnectionKeyName)
063.    {
064.        sqlConnectionKeyName = SqlConnectionKeyName;
065.        sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
066.        sqlConnection = new SqlConnection(sqlConnectionString);
067.    }
068. 
069.    /// <summary>
070.    /// Use sql connection string by user define.
071.    /// </summary>
072.    public SqlDatabaseManager(string SqlConnectionKeyName, string SqlConnectionString)
073.    {
074.        sqlConnectionKeyName = SqlConnectionKeyName;
075.        sqlConnectionString = SqlConnectionString;
076.        sqlConnection = new SqlConnection(sqlConnectionString);
077.    }   
078.    #endregion
079. 
080.    #region ========== Property ==========
081.    /// <summary>
082.    /// Gets or sets Sql connection key name from web.config.
083.    /// </summary>
084.    public virtual string ConnectionKeyName
085.    {
086.        get { return sqlConnectionKeyName; }
087.        set
088.        {
089.            sqlConnectionKeyName = value;
090.            sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
091.            sqlConnection = new SqlConnection(sqlConnectionString);  
092.        }
093.    }
094. 
095.    /// <summary>
096.    /// Gets or sets Sql connection.
097.    /// </summary>
098.    public virtual string ConnectionString
099.    {
100.        get { return sqlConnectionString; }
101.        set
102.        {
103.            sqlConnectionString = value;
104.            sqlConnection = new SqlConnection(sqlConnectionString);
105.        }
106.    }
107. 
108.    /// <summary>
109.    /// Gets or sets Sql command.
110.    /// </summary>
111.    public virtual string CommandString
112.    {
113.        get { return sqlCommandString; }
114.        set
115.        {
116.            sqlCommandString = ConvertDateCommand(value);
117.            sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
118. 
119.            commandMessage = "You must execute command.";
120.            commandSuccess = false;
121.            rowsAffected = 0;
122. 
123.            if (transaction)
124.                sqlCommand.Transaction = sqlTransaction;
125.        }
126.    }
127. 
128.    /// <summary>
129.    /// Check for Sql command.
130.    /// </summary>
131.    public virtual bool IsSuccess
132.    {
133.        get { return commandSuccess; }
134.    }
135. 
136.    /// <summary>
137.    /// Gets message from Sql command.
138.    /// </summary>
139.    public virtual string Message
140.    {
141.        get { return commandMessage; }
142.    }
143. 
144.    /// <summary>
145.    /// Gets Number of rows affected.
146.    /// </summary>
147.    public virtual int RowsAffected
148.    {
149.        get { return rowsAffected; }
150.    }
151.    #endregion
152. 
153.    #region ========== Method ==========
154.    /// <summary>
155.    /// Add the parameter value to the sql command.
156.    /// </summary>
157.    /// <param name="ParameterName">The name of Parameter.</param>
158.    /// <param name="ParameterValue">The value to be added.</param>
159.    public virtual void AddParameter(string ParameterName, object ParameterValue)
160.    {
161.        sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
162.    }
163. 
164.    /// <summary>
165.    /// Start Sql Transaction.
166.    /// </summary>
167.    public virtual void TransactionStart()
168.    {
169.        transaction = true;
170.        errorCommand = new List<string>();
171. 
172.        if (sqlConnection.State != ConnectionState.Open)
173.            sqlConnection.Open();
174. 
175.        sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);   
176.    }
177. 
178.    /// <summary>
179.    /// Execute Sql Transaction.
180.    /// </summary>
181.    /// <returns>Result of transaction.</returns>
182.    public virtual bool ExecuteTransaction()
183.    {
184.        transaction = false;
185. 
186.        if (errorCommand.Count == 0)
187.        {
188.            sqlTransaction.Commit();
189. 
190.            commandMessage = "All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>";
191.            commandSuccess = true;
192.        }
193.        else
194.        {
195.            sqlTransaction.Rollback();
196. 
197.            string ErrorText = "Some command has error. <font color=\"red\">Transaction RollBack.</font><br />Error in: <br />";
198. 
199.            foreach (string aErrorSqlCommand in errorCommand)
200.            {
201.                ErrorText += aErrorSqlCommand + "<br />";
202.            }
203. 
204.            commandMessage = ErrorText;
205.            commandSuccess = false;
206.        }
207. 
208.        errorCommand.Clear();
209. 
210.        if (sqlConnection.State == ConnectionState.Open)
211.            sqlConnection.Close();
212. 
213.        sqlTransaction.Dispose();
214.        sqlCommand.Dispose();
215.        sqlConnection.Dispose();
216. 
217.        return commandSuccess;
218.    }
219. 
220.    /// <summary>
221.    /// Execute Query Sql command.
222.    /// </summary>
223.    /// <returns>Query data in DataTable.</returns>
224.    public virtual DataTable ExecuteQuery()
225.    {
226.        DataTable dataTable = new DataTable();
227. 
228.        try
229.        {
230.            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
231.            sqlDataAdapter.Fill(dataTable);
232.            sqlDataAdapter.Dispose();
233. 
234.            if (!transaction)
235.            {
236.                sqlCommand.Dispose();
237.                sqlConnection.Dispose();
238.            }
239. 
240.            commandMessage = "Command is successfully.";
241.            commandSuccess = true;
242.        }
243.        catch (Exception ex)
244.        {
245.            commandMessage = ErrorMessage(ex.Message);
246.            commandSuccess = false;
247.        }
248. 
249.        rowsAffected = dataTable.Rows.Count;
250. 
251.        return dataTable;
252.    }
253. 
254.    /// <summary>
255.    /// Execute Scalar Sql command.
256.    /// </summary>
257.    /// <returns>Object of value.</returns>
258.    public virtual object ExecuteScalar()
259.    {
260.        object Result = 0;
261. 
262.        try
263.        {
264.            if (transaction)
265.            {
266.                Result = sqlCommand.ExecuteScalar();
267.            }
268.            else
269.            {
270.                if (sqlConnection.State != ConnectionState.Open)
271.                    sqlConnection.Open();
272. 
273.                Result = sqlCommand.ExecuteScalar();
274.                sqlConnection.Close();
275. 
276.                sqlCommand.Dispose();
277.                sqlConnection.Dispose();
278.            }
279. 
280.            commandMessage = "Command is successfully.";
281.            commandSuccess = true;
282.        }
283.        catch (Exception ex)
284.        {
285.            commandMessage = ErrorMessage(ex.Message);
286.            commandSuccess = false;
287.            AddErrorCommand(sqlCommandString, ex.Message);
288.        }
289. 
290.        return Result;
291.    }
292. 
293.    /// <summary>
294.    /// Execute Non Query Sql command.
295.    /// </summary>
296.    /// <returns>Result of execute command.</returns>
297.    public virtual bool ExecuteNonQuery()
298.    {
299.        rowsAffected = 0;
300. 
301.        try
302.        {
303.            if (transaction)
304.            {
305.                rowsAffected = sqlCommand.ExecuteNonQuery();
306.            }
307.            else
308.            {
309.                if (sqlConnection.State != ConnectionState.Open)
310.                    sqlConnection.Open();
311. 
312.                rowsAffected = sqlCommand.ExecuteNonQuery();
313.                sqlConnection.Close();
314. 
315.                sqlCommand.Dispose();
316.                sqlConnection.Dispose();
317.            }
318. 
319.            commandMessage = "Command is successfully.";
320.            commandSuccess = true;
321.        }
322.        catch (Exception ex)
323.        {
324.            commandMessage = ErrorMessage(ex.Message);
325.            commandSuccess = false;
326.            AddErrorCommand(sqlCommandString, ex.Message);
327.        }
328. 
329.        return commandSuccess;
330.    }
331. 
332.    /// <summary>
333.    /// Build error message.
334.    /// </summary>
335.    /// <param name="Message">Message string.</param>
336.    /// <returns>Error message string.</returns>
337.    protected virtual string ErrorMessage(string MessageString)
338.    {
339.        return "<font color=\"red\">Command error.</font> " + MessageString;
340.    }
341. 
342.    /// <summary>
343.    /// Add error sql command to string collections.
344.    /// </summary>
345.    /// <param name="commandString">The sql command.</param>
346.    /// <param name="errorMessage">The error message.</param>
347.    protected virtual void AddErrorCommand(string commandString, string errorMessage)
348.    {
349.        errorCommand.Add(commandString + " <font color=\"red\">[Error message: " + errorMessage + "]</font>");
350.    }
351. 
352.    /// <summary>
353.    /// Convert native command to sql command.
354.    /// </summary>
355.    /// <param name="commandString">The native sql command.</param>
356.    /// <returns>The standard sql command.</returns>
357.    protected virtual string ConvertDateCommand(string commandString)
358.    {
359.        string SmallDateTimePattern = "[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
360.        Regex SmallDateTimeRgx = new Regex(SmallDateTimePattern);
361. 
362.        foreach (Match SmallDateTimeMatchCase in SmallDateTimeRgx.Matches(commandString))
363.        {
364.            string MatchCasePattern = "^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]";
365.            Regex MatchCaseRgx = new Regex(MatchCasePattern);
366.            Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
367.            string TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
368. 
369.            commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(SmallDateTime, ").Replace(")", ", 103)"));
370.        }
371. 
372.        string DateTimePattern = "[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
373.        Regex DateTimeRgx = new Regex(DateTimePattern);
374. 
375.        foreach (Match DateTimeMatchCase in DateTimeRgx.Matches(commandString))
376.        {
377.            string MatchCasePattern = "^[dD][aA][tT][eE][tT][iI][mM][eE]";
378.            Regex MatchCaseRgx = new Regex(MatchCasePattern);
379.            Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
380.            string TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
381. 
382.            commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(DateTime, ").Replace(")", ", 103)"));
383.        }
384. 
385.        return commandString;
386.    }
387.    #endregion
388.}
389.#endregion
390. 
391.#region ========== Class SqlConvert ==========
392./// <summary>
393./// Summary description for SqlConvert
394./// </summary>
395.public sealed class SqlConvert
396.{
397.    /// <summary>
398.    /// Convert to byte[].
399.    /// </summary>
400.    /// <param name="BinaryStream">File upload binary stream.</param>
401.    /// <param name="StreamLength">Lenght of File upload binary stream.</param>
402.    /// <returns>Byte[] of binary stream.</returns>
403.    public static byte[] ToVarBinary(Stream BinaryStream, int StreamLength)
404.    {
405.        BinaryReader BinaryRead = new BinaryReader(BinaryStream);
406.        byte[] binaryData = BinaryRead.ReadBytes(StreamLength);
407. 
408.        return binaryData;
409.    }
410. 
411.    /// <summary>
412.    /// Convert to DataTime DataType with d/M/yyyy format.
413.    /// </summary>
414.    /// <param name="DateString">DateTime sring.</param>
415.    /// <returns>Datetime Type.</returns>
416.    public static DateTime ToDateTime(string DateString)
417.    {
418.        //ควรกำหนด culture ใน web.config เป็น th
419.        //
420.        //ตัวอย่างใน web.config
421.        //<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>
422. 
423.        return DateTime.ParseExact(DateString, "d/M/yyyy", CultureInfo.InvariantCulture);
424.    }
425. 
426.    /// <summary>
427.    /// Convert to DataTime DataType with user define format.
428.    /// </summary>
429.    /// <param name="DateString">DateTime sring.</param>
430.    /// <param name="DateFormat">DateTime Format</param>
431.    /// <returns>Datetime Type.</returns>
432.    public static DateTime ToDateTime(string DateString, string DateFormat)
433.    {
434.        //ควรกำหนด culture ใน web.config เป็น th
435.        //
436.        //ตัวอย่างใน web.config
437.        //<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>
438. 
439.        return DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
440.    }
441.}
442.#endregion

Date : 2010-04-07 12:05:39 By : tungman
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : มาดู SqlDatabaseManager New Version ก่อนเอาไปลงไว้ใน Community
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)





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