当用户注册表单的时候,需要返回用户注册后的ID,这时候用存储过程的Output很方便。
后台代码:
public
partial
class
_Default : System.Web.UI.Page
{
string SqlConnectionString = " Server=(local);Initial Catalog=dbtest;Integrated Security=True " ;
protected void Page_Load( object sender, EventArgs e)
{
}
protected void btnSubmit_Click( object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(SqlConnectionString);
using (SqlCommand com = new SqlCommand())
{
try
{
con.Open();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = " add_users " ;
com.Parameters.Add( " @User_Name " , SqlDbType.VarChar, 20 );
com.Parameters[ " @User_Name " ].Value = this .txtUser.Text;
com.Parameters.Add( " @Pass_word " , SqlDbType.VarChar, 20 ).Value = this .txtPwd.Text;
com.Parameters.Add( " @Id " , SqlDbType.Int, 4 ).Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
this .lblTip.Text = com.Parameters[ 2 ].Value.ToString();
con.Close();
}
catch { }
}
}
}
{
string SqlConnectionString = " Server=(local);Initial Catalog=dbtest;Integrated Security=True " ;
protected void Page_Load( object sender, EventArgs e)
{
}
protected void btnSubmit_Click( object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(SqlConnectionString);
using (SqlCommand com = new SqlCommand())
{
try
{
con.Open();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = " add_users " ;
com.Parameters.Add( " @User_Name " , SqlDbType.VarChar, 20 );
com.Parameters[ " @User_Name " ].Value = this .txtUser.Text;
com.Parameters.Add( " @Pass_word " , SqlDbType.VarChar, 20 ).Value = this .txtPwd.Text;
com.Parameters.Add( " @Id " , SqlDbType.Int, 4 ).Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
this .lblTip.Text = com.Parameters[ 2 ].Value.ToString();
con.Close();
}
catch { }
}
}
}
存储过程代码:(数据库就三个字段UID、UserName、Password)
CREATE proc [dbo].[add_Users]
(@User_Name varchar( 20 ),@Pass_word varchar( 50 ),@Id int output)
as
insert into info(UserName,Password) values(@User_name,@Pass_word)
select @Id = max(UID) from info
(@User_Name varchar( 20 ),@Pass_word varchar( 50 ),@Id int output)
as
insert into info(UserName,Password) values(@User_name,@Pass_word)
select @Id = max(UID) from info
完整程序下载:下载