1

I'm trying to update a table in my SQL Server database with text from an input box on my site;

My table is MemberSite.dbo.Users and the columns within this table are:

ID (Auto incrementing) UserName, Password, ApiKey, VeriF

It's not updating my SQL Server table.

What I want this to do: take the input text and put it in my SQL Server table against the user that is logged in.

Here is some code web.config :

<add name="WRITER" 
     connectionString="Data Source=localhost;Initial Catalog=MembershipSite;User ID=test;Password=test!" 
     providerName="System.Data.SqlClient" />

Backend to button click;

protected void Save_Click(object sender, EventArgs e)
{
    SqlConnection conn = null;

    try
    {
        string sql = "UPDATE dbo.Users SET ApiKey = @API, VeriF = @verif WHERE UserName = @username";

        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WRITER"].ConnectionString);

        SqlCommand cmd = new SqlCommand(sql, conn);

        SqlParameter api = new SqlParameter();
        api.ParameterName = "@API";
        api.Value = APIinput;
        cmd.Parameters.Add(api);

        SqlParameter verif = new SqlParameter();
        verif.ParameterName = "@verif";
        verif.Value = Veri;
        cmd.Parameters.Add(verif);

        SqlParameter UserN = new SqlParameter();
        UserN.ParameterName = "@username";
        UserN.Value = User.Identity.Name;
        cmd.Parameters.Add(UserN);

        conn.Open();
    }
    finally
    {
        if (conn !=null)
            conn.Close();
    }
}
2
  • I remove the ip address from your connection string, don't post information like this. I put localhost instead ! Commented Jan 22, 2016 at 10:11
  • 1
    thank you!! i over looked that >.> Commented Jan 22, 2016 at 10:12

2 Answers 2

2

Because you never execute your command. Just add:

cmd.ExecuteNonQuery();

after you open your connection.

Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually. Like;

using(var conn = new SqlConnection(conString))
using(var cmd = conn.CreateCommand())
{
   // Set your CommandText
   // Add your parameters
   // Open your connection
   // Execute your command.
}
Sign up to request clarification or add additional context in comments.

2 Comments

reason im choosing this answer as both were right is because it provided me with abit more information :)
Aslo to add to this i had to alter my SQLParamaters from api.Value = APIinput; to api.Value = APIinput.Text;
1

You have missed cmd.ExecuteNonQuery() after connection.Open(). That's why the values are not updated

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.