using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Registration
{
public partial class WebForm1 : System.Web.UI.Page
{
//checking if there is a user with the same username
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from Table where UserName='" +FullName.Text +"'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
//SqlException was unhandled of type"System.Data.SQlClient.SqlException"
//was not handled in user code
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp == 1)
Response.Write("User Already Exists");
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Insert into my database table
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertuser = "insert into Table (Username,Email,Passwrod,Age,Degree) values (@username,@email,@password,@age,@degree)";
SqlCommand cmd = new SqlCommand(insertuser, conn);
cmd.Parameters.AddWithValue("@username" , FullName.Text);
cmd.Parameters.AddWithValue("@email", Email.Text);
cmd.Parameters.AddWithValue("@password", Password.Text);
cmd.Parameters.AddWithValue("@age", Age.Text);
cmd.Parameters.AddWithValue("@degree", Degree.Text);
cmd.ExecuteNonQuery();
Response.Write("Registration Successfull");
conn.Close();
}catch(Exception ex) {
Response.Write("Error: " + ex.ToString());
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:2)
Table
为reserved keyword,如果您的表名为表,则需要像[Table]
一样正确包装,我也建议你把你的桌子命名为有意义的,现在它的名字含糊不清。
你还必须使用try catch块来防止你的应用程序崩溃,并且不要使用连接数据库访问代码来调查你的每个方法,而不是创建一个帮助器类并在那里移动常用功能,只需将其调用到其他所有地方易于维护的可重用性。