SqlServer2008
前言
最近C#用到了sql server 2008的存儲過程,特此整理成文
流程步驟
1.獲取鏈接
SqlConnection myConnection = new SqlConnection(@"server=
主機名
;uid=賬號
;pwd=密碼
;database=數據庫名
;Trusted_Connection=no");
2..建立可以執行SQL語句的SqlCommand
SqlCommand MyCommand = new SqlCommand("
存儲過程名
", myConnection); //定義一個數據庫操作指令
3.指明調用的是存儲過程
MyCommand.CommandType = CommandType.StoredProcedure;//設置該語句是讀取存儲過程的
4.設置數據適配器
SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定義一個數據適配器
SelectAdapter.SelectCommand = MyCommand;//定義數據適配器的操作指令
5.執行存儲過程
try{
myConnection.Open();//打開數據庫連接
SelectAdapter.SelectCommand.ExecuteNonQuery();//執行數據庫查詢指令
myConnection.Close();//關閉數據庫
}catch (Exception e)
{
throw new Exception(e.ToString());
}
6.將結果存儲到DataSet里
DataSet MyDataSet = new DataSet();//定義一個數據集SelectAdapter.Fill(MyDataSet);//填充數據集
7.解析DataSet中的數據
DataTable dt = MyDataSet.Tables[0];//獲取查詢的結果表(因為只有一個)
列類型
變量別名= (列類型
)dt.Rows[0]["列名
"];
完整版
SqlConnection myConnection = new SqlConnection(@"server=`主機名`;uid=`賬號`;pwd=`密碼`;database=`數據庫名`;Trusted_Connection=no");
SqlCommand MyCommand = new SqlCommand("`存儲過程名`", myConnection); //定義一個數據庫操作指令
MyCommand.CommandType = CommandType.StoredProcedure;//設置該語句是讀取存儲過程的
SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定義一個數據適配器
SelectAdapter.SelectCommand = MyCommand;//定義數據適配器的操作指令
try{
myConnection.Open();//打開數據庫連接
SelectAdapter.SelectCommand.ExecuteNonQuery();//執行數據庫查詢指令
myConnection.Close();//關閉數據庫
}catch (Exception e)
{
throw new Exception(e.ToString());
}
DataSet MyDataSet = new DataSet();//定義一個數據集SelectAdapter.Fill(MyDataSet);//填充數據集
DataTable dt = MyDataSet.Tables[0];//獲取查詢的結果表(因為只有一個)
`列類型` 變量別名= (`列類型`)dt.Rows[0]["`列名`"];