我的用户注册代码老是出错,大家帮看看啊(新手)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection( "server=.;database=reg;uid=sa;pwd=57744003; ");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into users(username,userpwd,email) values( ' " + txtusername.Text + " ', ' " + txtpassword.Text + " ', ' " + txtemail.Text + " ') ";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
Response.Write( " <script> alert( '注册成功 ') </script> ");
SqlConnection conn1=new SqlConnection( "server=.;database=reg;uid=sa;pwd=57744003; ");
conn1.Open();
SqlCommand cmd1 = new SqlCommand( "select count(*) from users where username= ' " + txtusername.Text + " ' ", conn);
int count = Convert.ToInt32(cmd1.ExecuteScalar());
if (count > 0)
{
Label1.Text = "用户已存在! ";
}
conn.Close();
}
catch (Exception ee)
{
Response.Write( "出错了 ");
}
}
}
这是代码,新手 代码毛病非常多 麻烦高手们帮看下啊 谢谢啦
[解决办法]
LZ应该先理清逻辑,大体改如下
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection( "server=.;database=reg;uid=sa;pwd=57744003; ");
try
{
conn.Open();
SqlCommand cmd1 = new SqlCommand( "select count(*) from users where username= ' " + txtusername.Text + " ' ", conn);
int count = Convert.ToInt32(cmd1.ExecuteScalar());
if (count > 0)
{
Label1.Text = "用户已存在! ";
return;
}
conn.Close();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into users(username,userpwd,email) values( ' " + txtusername.Text + " ', ' " + txtpassword.Text + " ', ' " + txtemail.Text + " ') ";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
Response.Write( " <script> alert( '注册成功 ') </script> ");
}
catch (Exception ee)
{
Response.Write( "出错了 ");
}
}