我目前正在使用SQL数据库,我的任务是编写注册表单。我已经获得了注册表格,但我需要检查是否已经使用了用户名。在我的代码中,用户名采用电子邮件的形式。我的代码有效,但实际上,允许多个用户名。 HEre是我的代码:
protected void registerUser(Object src, EventArgs e)
{
Response.Write("you have connected to your .cs page add records");
get_connection();
try
{
connection.Open();
command = new SqlCommand("INSERT INTO subscribers (FirstName, LastName, Email, Password)" +
" VALUES (@FirstName, @LastName, @Email, @Password)", connection);
command.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("@LastName", txtLastName.Text);
command.Parameters.AddWithValue("@Email", txtEmail.Text);
command.Parameters.AddWithValue("@Password", txtPassword.Text);
command.ExecuteNonQuery();
//connection.Close();
}
catch(Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text += "<br /><b>Record has been added</b>";
//lblInfo.Text = "<b>Server Version:</b> " + connection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + connection.State.ToString();
}
}
要检查用户名是否已被用过,我正在考虑使用&#34; If Then&#34; #34;尝试&#34;区域,但我不确定我需要什么编码。任何帮助或建议将不胜感激。
答案 0 :(得分:1)
你可以这样写:
string cmdText = @"IF NOT EXISTS(SELECT 1 FROM subscribers where Email = @Email)
INSERT INTO subscribers (FirstName, LastName, Email, Password)
VALUES (@FirstName, @LastName, @Email, @Password)"
command = new SqlCommand(cmdText, connection);
......
答案 1 :(得分:0)
您可以尝试以下代码:
{{1}}
如果结果为0则表示已经存在,否则插入新记录。