.Net Project/ADO.NET 3.5
22장 ADO.NET 연결 이벤트 (WinLinqDataSet)
Magic_kit
2009. 9. 30. 16:08
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WinLinqDataSet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection
("server=.;database=AddressBook;uid=AddressBook;pwd=1234;");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select *From AddressBook";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "AddressBook");
//LINQ를 사용해서 Listbox에 아이템 추가해보자
- DataSet을 사용하면 다른 많은 데이터 소스에서 사용 할 수 있는
동일 한 쿼리 기능을 사용하여 보다 풍부한 쿼리 기능을 DataSet에
빌드 가능
- Linq to Dataset 사용하면 DataSet 개체에 캐시된 데이터를 쉽고
빠르게 쿼리 가능하며, 특히 Linq to DataSet을 사용하면 별도의
쿼리 언어를 사용하는 대신 프로그래밍 언어 자체에서 쿼리를 작성
할 수 있으므로 간편하게 쿼리 가능합니다. |
var q = ds.Tables[0].AsEnumerable(); //DataTable을 Linq 타입
//이름 순으로 정렬(가,나,다,라 순으로)
var addr = from ad in q orderby ad.Field<string>("Name")
select ad;
foreach (var item in addr)
{
listBox1.Items.Add(item.ItemArray[1] + ","
+ item.ItemArray[2] + "," + item.ItemArray[3]);
}
con.Close();
}
}
}
//DataSet반복
DataTable dt = new DataTable();
dt = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
listBox2.Items.Add(dt.Rows[i]["Name"]
+ "," + dt.Rows[i]["Mobile"]);
}
//DataReader로 출력
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string s = dr["Name"].ToString() + "," + dr.GetString(2);
listBox3.Items.Add(s);
}
con.Close(); |