.NET Logo
Welcome Guest Search | Active Topics | Members | Log In | Register

การติดต่อฐานข้อมูลผ่าน ODBC Options · View
paedotnet
Posted: Friday, September 19, 2008 11:58:44 PM

Rank: มือเทพ
Groups: Member

Joined: 12/6/2007
Posts: 344
Location: bkk

การติดต่อฐานข้อมูลผ่าน ODBC
ก่อนที่จะใช้งาน ODBC ได้จะต้องทำการ Set ค่า User DSN ก่อนให้ไปที่
control panel->administrative tool ->Data Source (ODBC)
จากนั้นจะมีหน้าต่าง ODBC Data Source Administrator เกิดขึ้นมา
ให้เลือก แท็บ User DSN แล้วคลิกที่ปุ่ม Add... จากนั้นจะมีหน้าต่าง Create
New Data Source เกิดขึนมา
ให้เลือก SQL Server Driver  แล้วคลิกที่ปุ่ม Finish จากนั้นจะมีหน้าต่าง
Create a New Data Source to SqL server  ให้ใส่ชื่อในช่อง Name
และใส่ instance ของฐานข้อมูลในช่อง Server (ถ้าใช้ Sql server เวอร์ชั่นเต็มก็ใส่ . หรือ (local) แต่ถ้าใช้ express ก็ใส่ .\sqlexpress
ดังรูป

จากนั้นคลิกทีปุ่ม Next และก็คลิกที่ปุ่ม Next พอเจอหน้า ที่ใช้เลือก
ฐานข้อมูลก็ให้ / หน้า Change the default database to: ให้เลือกฐานข้อมูล
ที่ต้องการในตัวอย่างจะใช้ฐานข้อมุล Northwind จากนั้นคลิก Next แล้ว Finish แล้วจะกลับมาหน้า
แรก จะเห็นได้ว่ามีชื่อ testodbc ถูกสร้างขึ้นมาแล้วดังรูป


ตอนนี้เราก็สามารถที่จะติดต่อ ODBC ได้แล้วต่อไปก็เขียนโปรแกรมกัน
ตัวอย่างโค้ด
จะเป็นการดึงข้อมูลมาจาก table Customers ผ่าน ODBC
ในการที่จะติดต่อ odbc นั้นสิ่งแรกจะต้อง เพิ่ม using System.Data.Odbc;
ก่อนส่วนเรื่องของการติดต่อจะคล้ายๆกับการติดต่อฐานข้อมูลโดยใช้ SqlConnection ทั่วไป
แต่ต่างกันที่ connectionstring คือ สำหรับ odbc จะใช้ dsn=ชื่อ name ที่กำหนดใน user dsn เท่านั้น


using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc;
namespace ODBCConnectionss
{
    class Program
    {
        static void Main(string[] args)
        {
            string constr = "DSN=testodbc";
            OdbcConnection con = new OdbcConnection(constr);
            con.Open();
            string comstr = "SELECT * FROM Customers";
            OdbcCommand com = new OdbcCommand(comstr, con);
            OdbcDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader[4].ToString());
            }
            reader.Close();
            con.Close();
        }
    }
}

 



[With great power comes great responsibility]
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

YAFVision Theme Created by Jaben Cargman (Tiny Gecko)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.


Sponsored by