简体   繁体   中英

Storing table column value into variable (SQL Server)

I have been stuck on this problem for some time: I am trying to save a value from a column in a table (database), under a certain condition.

In the code below I am trying to compare the input of a textbox (sUserName) with a value in a column (UserName) in the table (aspnet_Membership). If these values are equal, I want to fetch the specific Email value in a column and save it as a string variable.

If UserName (column) does not equal sUserName (textbox), then I would like to display an error message (else statement). The Email and UserName column are in the same table

   string sUserName = txtBoxUsername.Text;

    SqlConnection conn2 = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\sunny\Visual Studio 2010\Projects\email\Prac 2\App_Data\aspnet_Membership.mdf;Integrated Security=True;User Instance=True");

    SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = sUserName", conn2);

Just add checking if user exist on your table to your code something like:

     string sUserName = txtBoxUsername.Text;
    SqlConnection conn2 = new SqlConnection("Your SQL Connection");

        SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = '"+ sUserName  + "'", conn2);

        SqlDataReader rdr = myCommand.ExecuteReader();
     if (dr.HasRows)
    {
          while (rdr.Read())
        {
                 // User exist - get email

                 string email = rdr["Email "].toString();

         }
    }
    else
    {
          //Error! user not exist
    }

Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM