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;
using System.Configuration;
namespace WinDataRelation
{
public partial class Form1 : Form
{
private DataSet ds; //전역변수로 사용
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString =
"server=.;database=Market;uid=Market;pwd=1234;";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText =
"Select CategoryID, CategoryName From Categories ";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds, "Categories");
cmd.CommandText =
"Select ProductID, CategoryID, ModelName
From Products";
da.SelectCommand = cmd;
da.Fill(ds, "Products");
//1번과 같은 방식을 사용할 경우, DB에서는 삭제 되지 않음
//[1] Categories와 Products간에 관계설정(메모리상)
//ds.Relations.Add(new DataRelation(
// "CP",
// ds.Tables[0].Columns["CategoryID"],
// ds.Tables[1].Columns["CategoryID"]));
//[2]제약조건 걸기
//부모 레코드 삭제시 자식이 참조하고 있으면 에러
ForeignKeyConstraint
- 값 또는 행이 삭제 되거나 업데이트될 때 기본키/외래키
관계에서 열 집합에 적용되는 동작 제한 나타 냅니다.
- 기본키 열과 함께 사용되어야 하며, 두 테이블이
부모/자식 관계
에 있을 때 부모 테이블에서 값을 삭제하면 자식 행에
다음 중
한 가지 결과가 나타날 수 있습니다
(자식 행이 삭제, 자식 열의 값이 Null 설정,
자식 열의 값이 기본값으로 설정, 예외 생성) |
ds.Tables["Products"].Constraints.Add(
new ForeignKeyConstraint("PK_Pro",
ds.Tables[0].Columns["CategoryID"],
ds.Tables[1].Columns["CategoryID"]));
//[3]삭제 규칙 적용
((ForeignKeyConstraint)
ds.Tables[1].Constraints["PK_Pro"])
.DeleteRule = Rule.None;
this.dataGridView1.DataSource = ds.Tables[0];
this.dataGridView2.DataSource = ds.Tables[1];
con.Close();
}
WriteXml
- XML 문서로 데이터만 쓰거나 데이터와 스키마를 사용
- 데이터와 스키마를 모두 쓰려면 mode 매개 변수를 포함하는
오버로드 중 하나를 사용하여 값을 WriteSchema 설정
ReadXml
- XML 스키마와 데이터를 DataTable 사용하여 읽어 올 수
있습니다.
- XML 문서에서 DataSet으로 데이터만 또는 데이터와 스키마를
모두 읽을 수 있으며, XMLReadMode 매개변수가 포함된
ReadXML 오버로드 하나를 사용하고 해당 값을
ReadSchema
설정 가능 합니다.
- DataTable의 XML 데이터만 또는 스키와 데이터를
모두 쓰려면, WriteXml 메서드 사용
- 스키마만 쓰려면 WriteXmlSchema메서드 사용 가능 |
//XML로 저장하기
private void button1_Click(object sender, EventArgs e)
{
ds.Tables[0].WriteXml
("C:\\Category.xml", XmlWriteMode.WriteSchema);
MessageBox.Show("XML저장 완료");
}
//XML로 읽어오기
private void button2_Click(object sender, EventArgs e)
{
DataTable read = new DataTable();
read.ReadXml(@"C:\\Category.xml");
this.dataGridView3.DataSource = read; //재바인딩
}
}
} |