I'm trying to update a SQL Server table using SqlCommand
, however, the table never gets updated when I run the code
My ASPX
:
<label id="lblEmail">Email:</label>
<asp:TextBox id="txtEmail" runat="server"/>
<label id="lblcode">Code:</label>
<asp:TextBox id="txtCode" runat="server"/>
<asp:ImageButton ID="btnSubmit" runat="server" ImageUrl="Images/Submit.gif" OnClick="btnSubmit_Click" Width="80px"/>
<asp:ImageButton ID="btnReset" runat="server" ImageUrl="Images/Reset.gif" OnClick="btnReset_Click" Width="80px"/>
This is my aspx.cs:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Email = txtEmail.Text.ToString();
string AttendingCode = txtRegCode.Text.ToString();
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=bkdb;User ID=sa;Password=sa");
SqlCommand cmd = new SqlCommand("UPDATE Registration SET [Attending] = 1 WHERE [Email] = '@Email' and [AttendingCode] LIKE '%@AttendingCode%'", con);
cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = Email;
cmd.Parameters.Add("@AttendingCode", SqlDbType.VarChar).Value = AttendingCode;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You don't need single apostrophes around your parameters. I suspect your parameters names (ie @Email) might be getting interpreted as literals.
Try removing the single apostrophes from around your parameters:
SqlCommand cmd = new SqlCommand("UPDATE Registration SET [Attending] = 1 WHERE [Email] = @Email and [AttendingCode] LIKE '%' + @AttendingCode + '%'", con);
It seems that you're not passing the parameters correct - you don't really need the quotes in your query, give this a shot:
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=bkdb;User ID=sa;Password=sa"))
using (var cmd = new SqlCommand(
"UPDATE Registration SET [Attending] = 1 WHERE [Email] = @Email and [AttendingCode] LIKE @AttendingCode",
con))
{
cmd.Parameters.AddWithValue("@Email", Email);
cmd.Parameters.AddWithValue("@AttendingCode", string.Format("%{0}%", AttendingCode));
con.Open();
cmd.ExecuteNonQuery();
}
Try just selecting the records using your WHERE clause. If the WHERE clause doesn't find any records nothing will be updated.
There may be trailing spaces or a case sensitivity issue that causes the WHERE to fail.
For more info: http://weblogs.asp.net/stevewellens/archive/2009/10/16/why-sql-updates-fail-three-reasons.aspx
Of course, you could mistakenly be updating a different database than you think.
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.