//帶參數的SQL語句 private void sql_param() { SqlConnection conn = new SqlConnection("server=WIN-OUD59R7EHCH;uid=sa;pwd=123456;database=china"); string sql =
//帶參數的SQL語句 private void sql_param() { SqlConnection conn = new SqlConnection("server=WIN-OUD59R7EHCH;uid=sa;pwd=123456;database=china"); string sql = "select *from test where uid=@myid"; SqlCommand comm = new SqlCommand(sql,conn); SqlParameter sp = comm.Parameters.Add("@myid",SqlDbType.Int); sp.Value = 2; comm.CommandType = CommandType.Text; SqlDataAdapter sda = new SqlDataAdapter(comm); DataSet ds = new DataSet(); sda.Fill(ds,"test"); this.dataGridView1.DataSource = ds.Tables[0]; } //標準的存儲過程 private void sql_proc() { SqlConnection conn = new SqlConnection("server=WIN-OUD59R7EHCH;uid=sa;pwd=123456;database=china"); conn.Open(); string sql = "proc_out"; SqlCommand comm = new SqlCommand(sql, conn); //將Command執行類型改為存儲過程的方式,預設為Text comm.CommandType = CommandType.StoredProcedure; //傳遞一個輸入參數,需要賦值 SqlParameter sp = comm.Parameters.Add("@uid",SqlDbType.Int); sp.Value = 1; //定義一個輸出參數,不許需要賦值。Direction用來描述參數的類型 //Direction預設為輸入參數,還有輸出參數和返回值 sp = comm.Parameters.Add("@output",SqlDbType.VarChar,200); sp.Direction = ParameterDirection.Output; /*定義過程的返回值參數,過程執行完之後,將把過程的返回值 * 賦給myreturn的Parameters賦值 */ sp = comm.Parameters.Add("myreturn",SqlDbType.Int); sp.Direction = ParameterDirection.ReturnValue; /*使用SqlDataAdapter將自動完成資料庫的打開和關閉過程, * 並將執行t-sql語句或存儲過程 * * 如果存儲過程只是執行相關操作,如級聯刪除或者更新, * 使用sqlcommand的execute方法即可 * */ try { SqlDataAdapter sda = new SqlDataAdapter(comm); DataSet ds = new DataSet(); comm.ExecuteNonQuery(); //在執行完存儲過程之後,可得到輸出參數 string myout = comm.Parameters["@output"].Value.ToString(); //列印輸出參數 MessageBox.Show("列印輸出參數:" + myout); //列印存儲過程返回值 myout = comm.Parameters["myreturn"].Value.ToString(); MessageBox.Show("存儲過程返回值:" + myout); sda.Fill(ds, "test"); this.dataGridView1.DataSource = ds.Tables[0]; } catch (Exception e) { MessageBox.Show(e.Message); } finally { conn.Close(); } } //簡易的存儲過程的使用 private void jyc() { SqlConnection conn = new SqlConnection("server=WIN-OUD59R7EHCH;uid=sa;pwd=123456;database=china"); string sql = "execute proc_out 1,'12'"; SqlCommand comm = new SqlCommand(sql,conn); SqlDataAdapter da = new SqlDataAdapter(comm); DataSet ds = new DataSet(); da.Fill(ds,"test"); this.dataGridView1.DataSource = ds.Tables[0]; }
存儲過程
create proc proc_out @uid int,@output varchar(200) output as --select結果集 select *from test where uid=@uid set @output = '記錄總數:'+convert(varchar(10),(select count(*) from test)) return 200; go