错误显示:ExecuteScalar: Connection property has not been initialized and exists = (int)cmd.ExecuteScalar() > 0;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = @UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (@UserID,@FName, @LName, @PhoneNo, @Address, @Email, @UserName, @Password, @Points, @Role)");
try
{
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@UserID", UserID);
cmd.Parameters.AddWithValue("@FName", tbFName.Text);
cmd.Parameters.AddWithValue("@LName", tbLName.Text);
cmd.Parameters.AddWithValue("@PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("@Address", tbAddress.Text);
cmd.Parameters.AddWithValue("@Email", tbEmail.Text);
cmd.Parameters.AddWithValue("@UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("@Password", tbPassword.Text);
cmd.Parameters.AddWithValue("@Points", Points);
cmd.Parameters.AddWithValue("@Role", Role);
connection.Open();
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
}
首先声明连接的正确方法应该是什么,因为我之前尝试过放置它,但我遇到了 cmd 问题。
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = @UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}