Desc SQL附近的语法错误,cmd.ExecuteNonQuery()上显示错误

时间:2017-11-02 11:21:21

标签: c# sql-server

我正在尝试在C#中为会计应用程序发出一个Insert语句,我偶然发现了一些问题,这些问题表明它在第88行出现了错误,而这恰好落在了这里

private void button2_Click(object sender, EventArgs e)
{
    using (SqlConnection cn = new SqlConnection(constring))
    {
        cn.Open();
        if (choice.Text == "DEPOSIT")
        {
            double newAccBal = Convert.ToDouble(opening_amount.Text) + Convert.ToDouble(amount.Text);
            string newBal = newAccBal.ToString();
            string sql = "insert into credit (fullname,accountNo,opening_amount,amount,desc,newBal) values (@fullname,@accountNo,@opening_amount,@amount,@desc,@newBal)";
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                cmd.Parameters.AddWithValue("@fullname", fullname.Text);
                cmd.Parameters.AddWithValue("@accountNo", textBox3.Text);
                cmd.Parameters.AddWithValue("@opening_amount", opening_amount.Text);
                cmd.Parameters.AddWithValue("@amount", amount.Text);
                cmd.Parameters.AddWithValue("@desc", desc.Text);
                cmd.Parameters.AddWithValue("@newBal", newBal);

                try
                {
                    var msg = MessageBox.Show("Information to be Sent for Deposit" + Environment.NewLine + "Please Confirm to Continue?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (msg == DialogResult.Yes)
                    {
                        cmd.ExecuteNonQuery(); <------------------------------ This Area
                        string confirmation = "Full Name : '"+fullname.Text+"' "+Environment.NewLine+" Depositing Amount : '"+amount.Text+"' "+Environment.NewLine+" Description : '"+desc.Text+"' "+Environment.NewLine+" New Balance : '"+newBal+"'";
                        MessageBox.Show("Deposit Successful" + Environment.NewLine + "Information has been Saved for Records" + Environment.NewLine + "Confirmation is as follows" + Environment.NewLine + confirmation ,"Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    string sql2 = "update account_info set opening_amount = '"+newBal+"' where id='"+id.Text+"'";
                    using (SqlCommand cmd2 = new SqlCommand(sql2, cn))
                    {
                        cmd2.ExecuteNonQuery();
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
}

说desc附近的语法不正确并指向该行cmd.ExecuteNonQuery(),我缺少什么?

2 个答案:

答案 0 :(得分:2)

DESC是SQL中的保留字,是降序的缩写,用于ORDER BY子句。将它包装在SQL语句的方括号中。

答案 1 :(得分:0)

您将其中一列命名为desc。但是,这是一个reserved word。您将需要选择不同的列名称(可能是一个明智的选择)或使用一种方法来确保您的DBMS识别您的意思是您的列,而不是保留字。您可以使用[]来注释名称:[desc]应该有效。