使用C#添加到sql整数列

时间:2013-05-06 01:54:11

标签: c# asp.net sql sql-update executescalar

我正在尝试从我的C#后端更新SQL表,但它从未成功执行; mainServiceButton是linkName列中的预先存在的值。以下是我到目前为止的情况:

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();

这就是表格的创建方式:

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

每次点击链接(linkName)时,所需的结果是将clickCount增加1。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

除了隐藏错误的详细信息之外,

MessageBox.Show("not executed");不会对你有所帮助:你需要输出捕获的异常的详细信息以了解发生的事情。

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

  • mainServiceButton在SQL文本中内联不太可能是您想要的内容
  • SqlParameter有保证接受WHERE sanely的值
  • 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();

答案 1 :(得分:-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();