Reputation: 105
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();
}
}
Upvotes: 1
Views: 87
Reputation: 98740
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.
}
Upvotes: 2
Reputation: 350
You have missed cmd.ExecuteNonQuery()
after connection.Open()
. That's why the values are not updated
Upvotes: 1