//带参数的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