检查SQL数据库是否存在电子邮件地址If-then ASP.net

时间:2014-04-25 17:17:37

标签: asp.net sql sql-server vb.net

我试图检查SQL数据库,看看用户注册的电子邮件是否已经存在。如果是,那么我想要一个错误信息弹出窗口,说它已经注册了。如果没有,那么他们应该已经成功注册。这是我的表单中唯一需要的剩余支票。问题部分以下面的 * 标注。请帮忙!

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls


Public Class WebForm1
Inherits System.Web.UI.Page

Dim boolCar As Object

Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    ' declare database input variables
    Dim userId As Integer = 0
    Dim firstName As String = txtFirstName.Text
    Dim lastName As String = txtLastName.Text
    Dim hometown1 As String = txtHometown1.Text
    Dim state1 As String = txtState1.Text
    Dim zip1 As String = txtZipCode1.Text
    Dim hometown2 As String = txtHometown2.Text
    Dim state2 As String = txtState2.Text
    Dim zip2 As String = txtZipCode2.Text
    Dim phoneNum As String = txtPhoneNumber.Text
    Dim emailAddress As String = txtEmailAddress.Text
    Dim password As String = txtPassword.Text
    Dim boolCar As Boolean = False
    Dim boolUmary As Boolean = False

    If radYesNo.SelectedIndex = 0 Then
        boolCar = True
    Else
        boolCar = False
    End If

    If txtEmailAddress.Text.Contains("@umary.edu") Then
        boolUmary = True
    Else
        boolUmary = False
    End If

        If boolUmary = True And txtPassword.Text = txtRetypePassword.Text Then


        If (IsPostBack) Then
            ' this creates the connection. It assumes you have your SQL Express database file in the App_Data directory
            Dim sqlConn As New SqlConnection("Server=CISWEB\UMCISSQL2008;Database=StudentGov;UId=sa;Password=Password1;")

            Dim sqlCmd As New SqlCommand ' create the command object

            Dim _SqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing

            sqlCmd.Connection = sqlConn ' define the connection for the command object

            ' define the command using parameterized query 
            sqlCmd.CommandText = "INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (@txtFirstName, @txtLastName, @txtHometown1, @txtState1, @txtZipCode1, @txtHometown2, @txtState2, @txtZipCode2, @txtPhoneNumber, @txtEmailAddress, @txtPassword, @RadYesNo)"

            ' define the SQL parameter
            sqlCmd.Parameters.AddWithValue("@txtFirstName", txtFirstName.Text)
            sqlCmd.Parameters.AddWithValue("@txtLastName", txtLastName.Text)
            sqlCmd.Parameters.AddWithValue("@txtHometown1", txtHometown1.Text)
            sqlCmd.Parameters.AddWithValue("@txtState1", txtState1.Text)
            sqlCmd.Parameters.AddWithValue("@txtZipCode1", txtZipCode1.Text)
            sqlCmd.Parameters.AddWithValue("@txtHometown2", txtHometown2.Text)
            sqlCmd.Parameters.AddWithValue("@txtState2", txtState2.Text)
            sqlCmd.Parameters.AddWithValue("@txtZipCode2", txtZipCode2.Text)
            sqlCmd.Parameters.AddWithValue("@txtPhoneNumber", txtPhoneNumber.Text)
            sqlCmd.Parameters.AddWithValue("@txtEmailAddress", txtEmailAddress.Text)
            sqlCmd.Parameters.AddWithValue("@txtPassword", txtPassword.Text)
            sqlCmd.Parameters.AddWithValue("@RadYesNo", boolCar)


            sqlConn.Open() ' open connection
            sqlCmd.ExecuteNonQuery() ' execute the data insertion

            *****Dim message As String = String.Empty
            //' no idea whats going on here
            //' What needs to happen - IF the UMaryEmail value ISNULL THEN message = Registration successful + SendActivationEmail(userId)
            //' ELSE (IF UMaryEmail != ISNULL) message = Supplied email address already in use
            sqlCmd.CommandText = "SELECT VALUE = CASE WHEN LEN(ISNULL(UMaryEmail,'))=0 Then '" + txtEmailAddress.ToString + "' WHEN LEN(ISNULL(UMaryEmail,'))!=0 THEN UMaryEmail END FROM RegisteredUsers;"
                Select Case userId
                    Case -10
                        sqlCmd.CommandText = "SELECT RegisteredUsers.UMaryEmail FROM RegisteredUsers WHERE(RegisteredUsers.UMaryEmail = '" + txtEmailAddress.ToString + "');"
                        message = "Supplied email address has already been used."
                        Exit Select
                    Case Else
                        message = "Registration successful. An activation email has been sent to the email provided."
                        SendActivationEmail(userId)
                        Response.Redirect("ActivateAccount.aspx")
                        Exit Select
                End Select*****


                ClientScript.RegisterStartupScript([GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True)

                sqlConn.Close() ' close connection

        ElseIf txtPassword.Text <> txtRetypePassword.Text Then
                MsgBox("The passwords do not match!")

        ElseIf boolUmary = False Then
                MsgBox("Please use your UMary email address!")
        End If
    End If


End Sub

Private Sub SendActivationEmail(userId As Integer)
    Dim sqlString As String = "Server=CISWEB\UMCISSQL2008;Database=StudentGov;UId=sa;Password=Password1;"
    Dim ActivationCode As String = Guid.NewGuid().ToString()
    Using con As New SqlConnection(sqlString)
        Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
            Using sda As New SqlDataAdapter()
                sqlCmd.CommandType = CommandType.Text
                sqlCmd.Parameters.AddWithValue("@UserId", userId)
                sqlCmd.Parameters.AddWithValue("@ActivationCode", ActivationCode)
                sqlCmd.Connection = con
                con.Open()
                sqlCmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Using mm As New MailMessage("mariders@umary.edu", txtEmailAddress.Text)
        mm.Subject = "Account Activation"
        Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
        body += "<br /><br />Please click the following link to activate your account"
        body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("VB.aspx", Convert.ToString("VB_Activation.aspx?ActivationCode=") & ActivationCode) + "'>Click here to activate your account.</a>"
        body += "<br /><br />Thanks"
        mm.Body = body
        mm.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.live.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential("trialmaps2014@outlook.com", "12Password")
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        Try
            smtp.Send(mm)
        Catch ex As Exception
            MsgBox("Email was not sent")
        End Try
    End Using
End Sub
End Class

我尝试使用Select Case语句,如上所示,但由于某种原因它不起作用。所以我对如何将SQL查询的结果转换为将在IF-THEN语句中使用的VB变量感到困惑。

1 个答案:

答案 0 :(得分:0)

这可能就是你要找的东西:

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
   If txtEmailAddress.Text.Trim.EndsWith("@umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
      Dim con As New SqlConnection
      Dim cmdEmail As New SqlCommand
      Dim cmdRegistration As New SqlCommand
      Dim EmailCount As Integer = 0

      Try
         con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
         con.Open()

         cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
         EmailCount = cmdEmail.ExecuteScalar()

         If EmailCount <> 0 Then
            ' Declare database input variables '
            Dim userId As Integer = 0
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
            Dim hometown1 As String = txtHometown1.Text
            Dim state1 As String = txtState1.Text
            Dim zip1 As String = txtZipCode1.Text
            Dim hometown2 As String = txtHometown2.Text
            Dim state2 As String = txtState2.Text
            Dim zip2 As String = txtZipCode2.Text
            Dim phoneNum As String = txtPhoneNumber.Text
            Dim emailAddress As String = txtEmailAddress.Text
            Dim password As String = txtPassword.Text
            Dim boolCar As Boolean = False
            Dim boolUmary As Boolean = False

            If radYesNo.SelectedIndex = 0 Then
               boolCar = True
            Else
               boolCar = False
            End If

            ' Define the command using parameterized query '
            cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (@txtFirstName, @txtLastName, @txtHometown1, @txtState1, @txtZipCode1, @txtHometown2, @txtState2, @txtZipCode2, @txtPhoneNumber, @txtEmailAddress, @txtPassword, @RadYesNo)", con)

            ' Define the SQL parameter '
            cmdRegistration.Parameters.AddWithValue("@txtFirstName", txtFirstName.Text)
            cmdRegistration.Parameters.AddWithValue("@txtLastName", txtLastName.Text)
            cmdRegistration.Parameters.AddWithValue("@txtHometown1", txtHometown1.Text)
            cmdRegistration.Parameters.AddWithValue("@txtState1", txtState1.Text)
            cmdRegistration.Parameters.AddWithValue("@txtZipCode1", txtZipCode1.Text)
            cmdRegistration.Parameters.AddWithValue("@txtHometown2", txtHometown2.Text)
            cmdRegistration.Parameters.AddWithValue("@txtState2", txtState2.Text)
            cmdRegistration.Parameters.AddWithValue("@txtZipCode2", txtZipCode2.Text)
            cmdRegistration.Parameters.AddWithValue("@txtPhoneNumber", txtPhoneNumber.Text)
            cmdRegistration.Parameters.AddWithValue("@txtEmailAddress", txtEmailAddress.Text)
            cmdRegistration.Parameters.AddWithValue("@txtPassword", txtPassword.Text)
            cmdRegistration.Parameters.AddWithValue("@RadYesNo", boolCar)

            cmdRegistration.ExecuteNonQuery()
         Else
            ' Duplicate Email Exist Error Message '            
         End If
      Catch ex AS Exception
         ' Error Executing One Of The SQL Statements '
      Finally
         con.close()
      End Try      
   Else
      ' Throw Error Message '
   End If
End Sub

如果这回答了您的问题,请将此信息标记为“已回答”。

谢谢!