Pregunta

I am trying to update a SQL table from my C# backend, but it never successfully executes; mainServiceButton is a pre-existing value in the linkName column. Here is what I have so far:

conn.Open();
       string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = mainServiceButton";
       SqlCommand cmd = new SqlCommand(qry, conn);
       try
       {
           cmd.ExecuteScalar();
       }
       catch
       {
           MessageBox.Show("not executed");
       }
        conn.Close();

This is how the table was created:

CREATE TABLE clickStream(
click_ID int identity(1,1),
linkName nvarchar(50) not null,
clickCount int,
PRIMARY KEY(click_ID));

The desired result is to increase the clickCount by 1 every time a link(linkName) is clicked on. Any Suggestions?

¿Fue útil?

Solución

MessageBox.Show("not executed"); is not going to help you much except to obscure the details of the error: you need to instead output the details of the caught exception to understand what happened.

Addressing this and other suggestions made in comments...

  • mainServiceButton nakedly inline in the SQL text not possibly being what you want
  • a SqlParameter being warranted to accept a value for the WHERE sanely
  • ExecuteNonQuery() instead of ExecuteScalar() being the right call

..., see what sort of mileage you get with this instead:

conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = @linkName";
SqlCommand cmd = new SqlCommand(qry, conn);
// Use a SqlParameter to correct an error in the posted code and do so safely.
cmd.Parameters.Add(new SqlParameter("@linkName", "mainServiceButton"));
try
{
    cmd.ExecuteNonQuery(); // not ExecuteScalar()
}
catch (SqlException sex)
{
    // Output the exception message and stack trace.
    MessageBox.Show(sex.ToString());
}
conn.Close();

Otros consejos

Try the below, not tested so you may need to fix minor bugs:

conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = 'mainServiceButton';SELECT @@ROWCOUNT;";
SqlCommand cmd = new SqlCommand(qry, conn);
try
{
    int rowsAffected = (int)cmd.ExecuteScalar();
    if (rowsAffected != 1)
        throw new ApplicationException("Rows affected should be 1, " + rowsAffected + " were affected.");
}
catch (Exception ex)
{
    MessageBox.Show("Not executed successfully, exception: " + ex.ToString());
}
conn.Close();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top