การเขียนโปรแกรมติดต่อ Database
ในตัวอย่างต่างๆผมจะใช้ ฐานข้อมูล northwind นะครับ โดยการนำ Northwind เข้ามาใน Microsoft sqlserver 2005
ให้เปิด Microsoft SqlServer 2005 ขึ้นมา แล้วไปที่ File->Open->File...
ดังรูปที่

จากนั้นจะมีหน้าต่าง Open File เกิดขึ้นมา ให้ไปเลือกไฟล์ Microsoft SQL Server Query File ที่ชื่อ Northwind
จากนั้นคลิกที่ปุ่ม Open จากนั้นก็จะกลับเข้ามาหน้า Query ใน Microsoft Sqlserver ให้เราทำการ execute (หรือกด F5) แล้ว ไป Refresh ตรง folder ที่ชื่อ Databases ที่อยู่ใน Object Explorer (ถ้าไม่มี Object Explorer ก็ไปที่ แถบเมนู ที่ชื่อ View->Object Explorer
หลังจากที่เราได้นำฐานข้อมูลที่ชื่อ Northwind เข้ามาแล้ว ต่อจากนี้เราจะมาเริ่มเขียนโปรแกรมติดต่อฐานข้อมูลกันโดย
ในส่วนนี้ผมจะอธิบายถึง การ select,delete,update,insert,DataTable ฯ
คลาสของ System.Data.SqlClient ได้แก่
SqlConnection ทำหน้าที่ในการเชื่อมต่อกับฐานข้อมูล
SqlCommand ทำหน้าที่ในการใช้งานคำสั่ง SQL Query ต่างๆเช่น SELECT,UPDATE,DELETE,INSERT ฯ
SqlDataAdapter ทำหน้าที่เป็นตัวกลางเชื่อมต่อระหว่าง DataSource และ DataSet
SqlDataReader ทำหน้าทำหน้าที่อ่านข้อมูลที่ได้จากการ Execute คำสั่ง
SqlError ทำหน้าทีจัดการกับข้อผิดพลาดต่างๆ
SqlParameter ทำหน้าที่จัดการกับ parameter
SqlTransaction ทำหน้าที่จัดการกับ Transaction ต่างๆ
เปิด Visual Studio 2008 หรือ 2005 ขึ้นมา
ไปที่ File->New->Project เลือก Visual C# ->Console Application
ในการเชื่อมต่อฐานข้อมูลนั้นมีสิ่งที่สำคัญคือ
รูปแบบที่จะกำหนดการเชื่อมต่อ
string constr = "Server = (local);Database =Northwind;Integrated Security = SSPI";
ตรง Server = (local) เป็นการกำหนด server ที่จะเชื่อมปกติถ้าเราติดตั้ง instance เดียวเช่น Microsoft SQLServer Express เราจะใช้ (local)/SqlExpress หรือ ./SqlExpress แต่ในตัวอย่างนี้ผมติดตั้งเป็น เวอร์ชั้นเต็ม
ผมก็ใช้ (local) หรือ . แทนก็ได้
ตรง Server เราอาจจะใช้ ตัวอื่นแทนก็ได้เช่น
Data Source = (local)
หรือ
address = (local)
หรือ
network address =(local)
หรือ
addr = (local)
ส่วน Database เป็นการกำหนดชื่อฐานข้อมูลที่ต้องการติดต่อเช่น northwind หรืออาจจะใช้ Initial Catalog ก็ได้
ส่วน Integrated Security เป็นการกำหนด Authentication Mode ค่าของตัวนี้สามารถเป็น true,sspi,no,false,yes หรืออาจจะใช้ Trusted_Connection แทนก็ได้
ตัวอย่างการกำหนดการเชื่อมต่อ
string constr = "Data Source = (local);Initial Catalog = Northwind;Integrated Security = SSPI";
หรือ
string constr = "Data Source = (local);Initial Catalog =northwind;User id = aaa; Password =123";
หรือ
string constr = "Server =(local);Database = northwind;Trusted_Connection =true";
ตัวอย่างการใช้งาน SELECT เพื่อดูข้อมูลจากตาราง Shippers ในฐานข้อมูล Northwind
using System;
using System.Data;
using System.Data.SqlClient;
public class TestSelect
{
public static void Main()
{
string constr = "Server = (local);Database =Northwind;Integrated Security=SSPI";
string cmdstr = "SELECT * FROM Shippers"; //กำหนดคำสั่ง sql
SqlConnection con = new SqlConnection();
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdstr;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader(); //สร้าง reader เพื่ออ่านข้อมูล
while (reader.Read())
{
Console.WriteLine("ShipperID : {0}\nShipperName : {1}", reader[0], reader[1]);
Console.WriteLine();
}
reader.Close();
con.Close();
Console.ReadLine();
}
}
ผลลัพธ์แสดงดังรูป

การใช้งาน ExecuteScalar
ExecuteScalar จะใช้กับ function Scalar ต่างๆเช่น COUNT,MAX,MIN ฯ
ตัวอย่างการนับจำนวนแถวทั้งหมด
using System;
using System.Data;
using System.Data.SqlClient;
public class TestSelect
{
public static void Main()
{
SqlConnection con = new SqlConnection("Data Source = .;Database =Northwind;Integrated Security = SSPI");
SqlCommand com = new SqlCommand("SELECT COUNT(*) FROM Shippers", con);
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
Console.ReadLine();
}
}
ตัวอย่างการ หาค่าสูงสุด (MAX)
using System;
using System.Data;
using System.Data.SqlClient;
public class TestSelect
{
public static void Main()
{
SqlConnection con = new SqlConnection("Data Source = .;Database =Northwind;Integrated Security = SSPI");
SqlCommand com = new SqlCommand("SeLECT MAX(Freight) AS Max_Freight FROM Orders", con);
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
Console.ReadLine();
}
}
ผลลัพธ์จะได้ดังรูป

การ ใช้งาน ExecuteNonQuery
using System;
using System.Data;
using System.Data.SqlClient;
public class TestInsert
{
public static void Main()
{
SqlConnection con = new SqlConnection("Data Source = .;Database =Northwind;Integrated Security = SSPI");
SqlCommand com = new SqlCommand(string.Format("INSERT INTO Shippers VALUES('{0}','{1}')","MyCompanys","(978)333-4322)"));
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
con.Close();
Console.ReadLine();
}
}
ผลลัพธ์จะมีแถวใหม่เกิดขึ้นมา
การใช้งาน Parameter
ในการใช้งาน Parameter เราจะกำหนด parameter ต่างๆโดยใช้ @ นำหน้าชื่อ parameter เช่น @name,@lastname
ตัวอย่างการใช้งาน parameter
using System;
using System.Data;
using System.Data.SqlClient;
public class TestInsert
{
public static void Main()
{
Console.WriteLine("Enter Companyname");
string shippername = Console.ReadLine();
Console.WriteLine("Enter phone");
string phone = Console.ReadLine();
string constr = "Server = (local);Database=northwind;Integrated Security =SSPI";
string comstr = "INSERT INTO Shippers VALUES(@name,@phone)";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(comstr, con);
SqlParameter param = new SqlParameter(); //กำหนด parameter
con.Open();
param.ParameterName = "@name"; //กำหนดชื่อของ parameter
param.SqlDbType = SqlDbType.NVarChar; //กำหนดชนิดที่จะเก็บเป็น parameter
param.Value = shippername; //กำหนดค่าที่จะให้กับ parameter
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "@phone";
param2.SqlDbType = SqlDbType.NVarChar;
param2.Value = phone;
cmd.Parameters.Add(param); //ต้องมีคำสั่งนี้เพื่อบอกว่าได้เพิ่มตัวแปรของ parameter เข้าไป
cmd.Parameters.Add(param2);
cmd.ExecuteNonQuery(); //ใช้ ExecuteNonQuery() เพื่อ Insert ข้อมูล
con.Close();
Console.ReadLine();
}
}
ผลลัพธ์จะมีแถวใหม่เกิดขึ้นมา
การใช้งาน UPDATE
ตัวอย่างโค้ด
using System;
using System.Data;
using System.Data.SqlClient;
public class TestUpdate
{
public static void Main()
{
string constr = "Server = (local);Database=northwind;Integrated Security =SSPI";
string comstr = "UPDATE Shippers SET CompanyName = @companyname WHERE Shipperid=5";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(comstr, con);
con.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "@companyname";
param.SqlDbType = SqlDbType.NVarChar;
param.Value = "
aabbcc@zz";
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
con.Close();
Console.ReadLine();
}
}
การเรียกดูข้อมูลโดยใช้ SELECT
ตัวอย่าง
using System;
using System.Data;
using System.Data.SqlClient;
public class TestSelect
{
public static void Main()
{
SqlConnection con = new SqlConnection("Server = .;Database=northwind;Integrated Security=true");
SqlCommand com = new SqlCommand("SELECT * FROM Shippers;SELECT TOP 10 * FROM Customers", con);//กำหนดให้เลือกมาสองตาราง
con.Open();
SqlDataReader reader = com.ExecuteReader();
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Show Shippers Table");
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + " " + reader.GetString(1));
}
reader.NextResult(); //แสดงตารางถัดไป
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Show Custimers Table");
while (reader.Read())
{
Console.WriteLine(reader[0] + " " + reader[1]+" "+reader[2]);
}
reader.Close();
con.Close();
Console.ReadLine();
}
}
ผลลัพธ์แสดงดังรูป

การ DELETE
using System;
using System.Data;
using System.Data.SqlClient;
public class TestDelete
{
public static void Main()
{
Console.WriteLine("Enter ShipperId For deleting");
int id = Convert.ToInt32(Console.ReadLine());
string constr = "Address = (local);Initial Catalog = Northwind;Integrated Security = SSPI";
string comstr = "DELETE FROM Shippers WHERE ShipperId = @id";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(comstr, con);
con.Open();
com.Parameters.Add("@id", SqlDbType.Int, 4, "ShipperID"); //กำหนด Parameter
com.Parameters["@id"].Value = id; //กำหนดค่าให้กับ parameter
com.ExecuteNonQuery();
con.Close();
}
}
ผลลัพธ์ให้ใส่ id ที่ต้องการลบลงไป แล้วไปตรวจสอบดูในฐานข้อมูล จะมีข้อมูลถูกลบตาม id ที่เรากำหนด
การใช้งาน DataTable
using System;
using System.Data;
using System.Data.SqlClient;
public class TestDataTable
{
public static void Main()
{
string constr = "Server = (local);Database=northwind;Integrated Security = SSPI";
string comstr = "SELECT * FROM Orders";
SqlConnection con = new SqlConnection();
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = comstr;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = reader.GetSchemaTable(); //กำหนด DataTable
foreach (DataRow r in dt.Rows)
{
foreach (DataColumn c in dt.Columns)
{
Console.WriteLine("Row : {0} , Col : {1}", r[c], c.ColumnName);
}
}
reader.Close();
con.Close();
Console.ReadLine();
}
}


[With great power comes great responsibility]