การเขียนโปรแกรมติดต่อฐานข้อมูลโดยใช้ OLE DB
OLE DB เป็นเทคโนโลยีตัวหนึ่งของ Microsoft ในการติดต่อกับฐานข้อมูล
ตัวอย่างเช่นใช้ OLE DB ติดต่อฐานข้อมูล Microsoft Access
แต่สามารถที่จะใช้ provider ติดต่อกับฐานข้อมูล อย่างอื่นได้เช่น SQL server,
DB2,Oracle,ODBC
ซึ่งจะติดต่อกับฐานข้อมูลใดนั้นจะต้องรู้ Provider ของฐานข้อมูลชนิดนั้นๆก่อน
ตัวอย่าง Provider และ ฐานข้อมูลที่ใช้ Provider นี้
MS Access -> Microsoft.Jet.OLEDB.4.0
MS SQL Server -> SQLOLEDB
DB2 -> DB2OLEDB
ODBC -> MSDASQL
Oracle -> MSDAORA
ในตัวอย่างนี้ผมจะทดสอบโดยใช้ provider ที่ชื่อ SQLOLEDB เพื่อติดต่อกับฐานข้อมูล Sql server
โดยจะใช้ฐานข้อมูลที่ชื่อ Northwind
ตัวอย่างโค้ด
ให้ using System.Data.OleDb; ด้วย
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string constr = "Provider = SQLOLEDB;Data Source = (local);Integrated Security = sspi;Initial catalog = northwind";
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string comstr = "SELECT * FROM Customers";
OleDbCommand com = new OleDbCommand();
com.CommandText = comstr;
com.Connection = con;
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[1].ToString());
}
reader.Close();
con.Close();
}
}
}
ผลลัพธ์
ดังรูป

*** ถ้ารันแล้วแสดงผลลัพธ์ออกมาดังรูปแสดงว่าไม่มีปัญหาสำหรับการใช้งาน provider ชนิดนี้
แต่ถ้ามีปัญหาคือมี Error เกิดขึ้นว่า
[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
แสดงว่ายังไม่ได้ enable ค่าบางค่าดังนั้นให้ไปที่
sql server configuration Manager
เลือกตรง SQL Server 2005 Network Configuration แล้วให้ Enable ค่าต่างๆดังรูป

(ถ้าใช้ เวอร์ชั่น Express ก็เลือกในส่วนของ SQLExpress)
หลังจากที่ Enable แล้วต่อไปให้ Restart Service ใหม่ไปที่
Control panel ->Administrative tools->Services->เลือก SQL Server(MSSQLSERVER) สำหรับเวอร์ชั่น เต็ม หรือ SQL Server (SQLEXPRESS)สำหรับเวอร์ชั่น express
จากนั้นเลือก stop service แล้ว start service อีกครั้งก็จะใช้งานได้
[With great power comes great responsibility]