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