-2

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?

4

2 回答 2

2

MessageBox.Show("not executed");除了掩盖错误的细节外,对您没有多大帮助:您需要输出捕获的异常的详细信息以了解发生了什么。

解决评论中提出的这个和其他建议......

  • mainServiceButtonSQL 文本中的裸内联可能不是您想要的
  • 一个SqlParameter被保证接受WHERE理智的价值
  • ExecuteNonQuery()而不是ExecuteScalar()正确的选择

...,看看你得到什么样的里程数:

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();
于 2013-05-06T02:49:54.520 回答
-1

尝试以下,未经测试,因此您可能需要修复小错误:

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();
于 2013-05-06T02:57:04.490 回答