public partial class signupuser : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
// sign up button click event
protected void Button1_Click(object sender, EventArgs e)
{
//Response.Write("<script>alert('Testing');</script>");
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tbl(email, password, full_name, user_name, dob, account_status) VALUES(@email, @password, @full_name, @user_name, @dob, @account_status)", con);
cmd.Parameters.AddWithValue("@full_name", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("@email", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@password", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("@user_name", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("@dob", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@account_status", "Pending");
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful. Go to User Login to Login.');</script>");
}
catch(Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}
这里是代码,我目前正在开发一个asp.net web应用程序,我正在使用SQL服务器,并试图使注册页面。我想从用户的输入被存储到数据库时,我点击按钮。现在所发生的是,我单击按钮,页面刷新,但没有数据添加到数据库中。我也没有收到"注册成功"的警告框;所以一定是出了什么问题。想法吗?
创建后检查连接是否立即打开是无用的。连接应该在尽可能短的时间内打开。就在执行命令对象之前。您必须删除以下代码:
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
但是您在创建cmd之前打开了连接。你应该这样使用连接:
using (var con = new SqlConnection(strcon))
{
var cmd = new SqlCommand("INSERT INTO member_master_tbl(email, password, full_name, user_name, dob, account_status) VALUES(@email, @password, @full_name, @user_name, @dob, @account_status)", con);
cmd.Parameters.AddWithValue("@full_name", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("@email", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@password", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("@user_name", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("@dob", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@account_status", "Pending");
cmd.connection.Open();
if (cmd.ExecuteNonQuery()>= 1)
{
Response.Write("<script>alert('Sign Up Successful. Go to User Login
to Login.');</script>");
}
}