DataSet
DataSet可以理解爲一個數據庫,但它是存在於應用程序中的微型數據庫。和數據庫一樣,DataSet中可以存放多張表(DataTable),表和表之間有着關係(DataRelation),DataRow爲Dataset的行,DataColumn爲DataSet的列。
上圖中的DataSet包含了兩個DataTable:Products和Categories。兩個表通過CategoryID建立外鍵約束,即DataRelation
那麼,DataSet中的數據從何而來呢?這就要談到Connection、Command和DataReader…
Connection
Connection並不是單純的一個類,而是包含了很多類,這些類的作用就是提供了數據庫連接。例如:連接SQL Server就是SqlConnection,連接Oracle就是OracleConnection。
由於他們都叫***Connection,所以統稱爲Connection
連接數據庫的前提是制定連接字符串,字符串中包含數據庫名字、位置、登錄的用戶名、密碼等
eg:
using System;
using System.Data.SqlClient;
namespace text
{
class Class_09_01
{
public statioc void Main(String[] args)
{
//數據庫連接情況各不相同,讀者可自行查閱資料
string strConn = "Initial Catalog=Northwind;Data Source=(local);User ID = ****;Password=**** ";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConn;
try
{
conn.Open();//打開數據庫
////////////
//數據庫操作
////////////
//...............
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("異常:無法連接到數據庫!");
}
}
}
連接上數據庫,接下來我們就可以用Command來獲取數據了
Command
和Connection一樣,Command也不是一個類,而是包含了很多類,如SqlCommand,OracleCommand等。
一個command對象表示要對數據庫執行的SQl語句或存儲過程。
對於查詢命令,可返回一個數字,這時可以用ExecuteScalar()執行
Command也可以執行數據庫的更新任務
eg:
using System;
using System.Data.SqlClient;
namespace ****
{
class Class_09_02
{
public static void Main(String[] args)
{
string strConn = "Initial Catalog=Northwind;Data Source=(local);User ID = ****;Password=**** ";
SqlConnection conn = new SqlConnection(strConn);
try
{
conn.open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText="select count(productID) From Products";
console.WriteLine("products 有{0}行",cmd.ExecuteScalar());
conn.Close();
}
catch(Exception e)
{
//*****************************
}
}
}
}
若是返回的不是一個數字,而是一張表呢?
DataReader
DataReader也是通過Command裏的ExecuteScalar()方法得到的,但是DataReader只會在內存中保存當前行的數據,而不會保存全部內容,可以用Read()方法讀取一行並使他前進到下一行。
eg:
using System;
using System.Data.SqlClient;
namespace text
{
class Class_09_01
{
public statioc void Main(String[] args)
{
//數據庫連接情況各不相同,讀者可自行查閱資料
string strConn = "Initial Catalog=Northwind;Data Source=(local);User ID = ****;Password=**** ";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConn;
try
{
conn.Open();//打開數據庫
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText="select CategoryID,CategoryName From Categories";
SqlDataReader reader = cmd.ExecuteReader();
//輸出結果
Console.WriteLine("{0}\t{1}","CategoryID","CategoryName");
Console.WriteLine();
while(reader.Read())
{
Console.WriteLine("{0}\t{1}",reader.GetInt32(0),reader.Getstring(1));
}
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("異常:無法連接到數據庫!");
}
}
}
結果
DataAdapter
當數據庫和DataSet中的數據不一致時,用來更新數據。此功能基於Command的4個對象
Command | 說明 |
---|---|
SelectCommannd | 用於在數據源中選擇記錄SQL命令 |
InsertCommand | 用於在數據源中插入新記錄的SQL命令 |
UpdateCommand | 用於更新數據源中的記錄的SQL命令 |
DeleteCommand | 用於從數據集刪除記錄的SQL命令 |
DataAdapter提供fill()方法來填充DataSet,在調用Fill()時,利用SelectCommand返回的DataReader來讀取數據。
eg:
using System;
using System.Data.SqlClient;
namespace text
{
class Class_09_01
{
public statioc void Main(String[] args)
{
//數據庫連接情況各不相同,讀者可自行查閱資料
string strConn = "Initial Catalog=Northwind;Data Source=(local);User ID = ****;Password=**** ";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConn;
try
{
conn.Open();//打開數據庫
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText="select RegionID,RegionDescription From Region";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = silcmd;
DataSet ds = new DataSet();
//填充數據
da.fill(ds);
conn.Close();
DataTable dt = ds.Tables[0];
Console.WriteLine("{0}\t{1}",dt.Columns[0],dt.Columns[1]);
foreach(DataRow r in dt.Rows)
{
Console.WriteLine("\t{0}\t{1}",r[0],r[1]);
}
}
catch(Exception e)
{
Console.WriteLine("異常:無法連接到數據庫!");
}
}
}
一個DataSet被創建時是空的,被填充之後有了數據和架構。
我們可以通過訪問Columns集合得到各列名
如果要更新數據,我們可以用DataAdapter中的Update()方法,他會自動檢測有無數據更新,如果有,則調用對應方法
eg:
using System;
using System.Data.SqlClient;
namespace text
{
class Class_09_01
{
static string strConn = "************(連接數據庫的名稱,密碼等)**************";
public static void CheckData()
{
SqlConnection conn = new SqlConnection(strConn);
try
{
conn.open()
SqlCommand cmd = new SqlCommand("select * from Region",conn);
SqlDataReader reader = new SqlDataReader();
DataTable dt = reader.GetSchemaTable();
Console.WriteLine("{0}\t{1}",dt.Columns[0],dt.Columns[1]);
while(reader.read())
{
Console.WriteLine("{0}\t{1}",reader[0],reader[1]);
}
}
catch(Exception e)
{
///////////////////*********************
}
}
public statioc void Main(String[] args)
{
SqlConnection conn = new SqlConnection(strConn);
try
{
conn.open();
SqlCommand selcmd = new SqlCommand();
selcmd.Connecction = conn;
selcmd.CommandText = "select * from Region";
SqlDataAdpter da = new SqlDataAdpter();
da.SelectCommand = selcmd;
DataSet ds = new DataSet();
da.File(ds);
conn.Close();
//利用SqlCommandBuilder自動建立
//Insert,updata和Delete Command
SqlCommandBuilder cb = new SqlCommandBuilder(da);
//添加數據
Console.WriteLine("輸入一個新的RegionDesCription:");
string newRegion = ConSole.ReadLine();
//吧新數據添加到DataSet
DataRow r = ds.Tables[0].Newrow();
r["RegionID"] = 5;
r["RegionDesCription"] = newRegion;
ds.Table[0].Rows.Add(r);
//更新數據庫
da.Update(ds);
CheckData();
//更新數據庫
Console.WriteLine("再輸入一個新的RegionDescription,它將取代剛纔的數據:");
newRegion = Console.WriteLine();
//更新DataSet中的數據
r = ds.Table[0].Select("RegionID = 5")[0];
r["RegionDescription"] = newRegion;
//更新數據庫
da.Update(ds);
CheckData();
//刪除數據
Console.WriteLine("刪除剛纔的數據:");
r.Delete();
da.Update(ds);
CheckData();
}
catch(Exception e)
{
///////////////////////////////////////////////////////////
}
}
}
}
本文章所有代碼都沒有在編譯器上運行檢驗,所以可能會有一些小錯誤,但是總體私立時對的
小白筆記 , 歡迎大家指點