C# WinApp database กับ extension method ก็ สะดวกสบายดีไปอีกแบบ
วันนี้นั่งทำ extension method เพลินไปถึง database แบ่งให้เล่นกันครับ
Code (C#)
public static class extDatabase
{
public static System.Data.SqlClient.SqlConnection ToSqlConnection(this string input)
{
System.Data.SqlClient.SqlConnection cnn;
try
{
cnn = new System.Data.SqlClient.SqlConnection(input);
cnn.Open();
}
catch { cnn = null; }
return cnn;
}
public static System.Data.OleDb.OleDbConnection ToOleDbConnection(this string input)
{
System.Data.OleDb.OleDbConnection cnn;
try
{
cnn = new System.Data.OleDb.OleDbConnection(input);
cnn.Open();
}
catch { cnn = null; }
return cnn;
}
public static System.Data.Odbc.OdbcConnection ToOdbcConnection(this string input)
{
System.Data.Odbc.OdbcConnection cnn;
try
{
cnn = new System.Data.Odbc.OdbcConnection(input);
cnn.Open();
}
catch { cnn = null; }
return cnn;
}
public static System.Data.DataTable ToDataTable(this string SQL,System.Data.SqlClient.SqlConnection cnn)
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.DataTable dt;
try
{
System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(SQL, cnn);
adapter.Fill(ds);
dt= ds.Tables[0];
}
catch { dt = null; }
return dt;
}
public static System.Data.DataTable ToDataTable(this string SQL, System.Data.OleDb.OleDbConnection cnn)
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.DataTable dt;
try
{
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(SQL, cnn);
adapter.Fill(ds);
dt = ds.Tables[0];
}
catch { dt = null; }
return dt;
}
public static System.Data.DataTable ToDataTable(this string SQL, System.Data.Odbc.OdbcConnection cnn)
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.DataTable dt;
try
{
System.Data.Odbc.OdbcDataAdapter adapter = new System.Data.Odbc.OdbcDataAdapter(SQL, cnn);
adapter.Fill(ds);
dt = ds.Tables[0];
}
catch { dt = null; }
return dt;
}
}
เวลาใช้งาน
ก็จะเป็นแบบนี้
Code (C#)
dataGridView1.DataSource = "SELECT *FROM Instrument_Pipet".ToDataTable(DATA_CSharp.Properties.Settings.Default.DATA_ALS_ContactConnectionString.ToSqlConnection());
Tag : .NET, Win (Windows App), C#, VS 2012 (.NET 4.x), Windows
Date :
2017-02-03 18:25:01
By :
lamaka.tor
View :
791
Reply :
4
ได้ลองเล่น SignalR บน Windows Form หรือยังครับ เผื่อมีไอเดียดีๆ ในการพัฒนา Application ครับ
Date :
2017-02-03 18:47:02
By :
mr.win
ลองบน ASP.Net ด้วยก็ดีนะครับ
Date :
2017-02-06 09:56:01
By :
mr.win
ผมทำประมาณนี้ครับ
Code (VB.NET)
Dim Con1 as new clsSql
Dim Con2 as new clsSql
Dim cmd as String
dim dtTemp as datatable
dim drAdd as datarow
Con1.Open("Server1")
Con2.Open("Server2")
cmd="Select * from TableName"
dtTemp=Con1.Execute(cmd)
cmd="Delete from TableName"
Con2.Execute(cmd)
drAdd=Con1.GetTable("TableName")
drAdd("Name")="MyName"
drAdd("Last_Name")="My Last Name"
Con1.InsertFromDr(drAdd,"TableName")
Date :
2017-02-06 10:12:00
By :
fonfire
Load balance : Server 02