SqlException:“nvarchar”附近的语法不正确

Posted

技术标签:

【中文标题】SqlException:“nvarchar”附近的语法不正确【英文标题】:SqlException: Incorrect syntax near 'nvarchar' 【发布时间】:2021-01-23 05:08:19 【问题描述】:

我收到了这个错误:

System.Data.SqlClient.SqlException: 'nvarchar' 附近的语法不正确。 “名称”附近的语法不正确。

尝试单击添加按钮时。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

namespace OOP_Draft

    public partial class Form1 : Form
    
        double amount, monthlyPay, totalPay;
        int years;

        private void btnReset_Click(object sender, EventArgs e)
        
            txtName.Clear();
            txtEmpno.Clear();
            txtEmail.Clear();
            txtDept.Clear();
            txtAmount.Clear();
            txtYears.Clear();
            lblPay.Text = "";
            lblTot.Text = "";
            rtxtReceipt.Clear();
        

        private void btnSubmit_Click(object sender, EventArgs e)
                   
            if(txtName.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else if (txtEmpno.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else if (txtEmail.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else if (txtDept.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else if (txtAmount.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else if (txtYears.Text == "")
            
                MessageBox.Show("Please fill up the form.");
            
            else
            
                amount = double.Parse(txtAmount.Text);
                years = int.Parse(txtYears.Text);
                monthlyPay = amount * 0.03 / (1 - 1 / Math.Pow(1 + 0.02, years * 12));
                totalPay = monthlyPay * years * 12;
                monthly = Convert.ToString(monthlyPay);
                monthly = String.Format("0:C", monthlyPay);
                lblPay.Text = (monthly);
                total = String.Format("0:C", totalPay);
                lblTot.Text = (total);
                txtAmount.Text = String.Format("0:C", amount);
            
        

        string monthly, total;

        private void btnEmail_Click(object sender, EventArgs e)
        
            try
            
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.Timeout = 10000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential("prestantesi@gmail.com", "ironhide13");
                MailMessage msg = new MailMessage();
                msg.To.Add(txtEmail.Text);
                msg.From = new MailAddress("prestantesi@gmail.com");
                msg.Subject = "Loan Receipt";
                msg.Body = rtxtReceipt.Text;
                client.Send(msg);
                MessageBox.Show("Email Sent.");
            
            catch(Exception ex)
            
                MessageBox.Show(ex.Message);
            

        

        private void btnAdd_Click(object sender, EventArgs e)
        
            SqlCommand cmd;
            SqlConnection con;

            con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Kim\Documents\SMEMCO.mdf;Integrated Security=True");
            con.Open();
            cmd = new SqlCommand("INSERT INTO LoanRecord (Employee Name, Employee Number, Department, Loan Amount, Years To Pay, Monthly Payment, Total Payment) VALUES (@Employee Name, @Employee Number, @Department, @Loan Amount, @Years To Pay, @Monthly Payment, @Total Payment)", con);
            cmd.Parameters.AddWithValue("@Employee Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Employee Number", txtEmpno.Text);
            cmd.Parameters.AddWithValue("@Department", txtDept.Text);
            cmd.Parameters.AddWithValue("@Loan Amount", txtAmount.Text);
            cmd.Parameters.AddWithValue("@Years To Pay", txtYears.Text);
            cmd.Parameters.AddWithValue("@Monthly Payment", lblPay.Text);
            cmd.Parameters.AddWithValue("@Total Payment", lblTot.Text);
            cmd.ExecuteNonQuery();
        

        private void btnDisplay_Click(object sender, EventArgs e)
        
            rtxtReceipt.AppendText("Loan Record" + "\t" + "\n");
            rtxtReceipt.AppendText("--------------------------------------------------------" + "\t" + "\n");
            rtxtReceipt.AppendText("Name:" + "\t" + "\t" + "\t" + "\t" + txtName.Text + "\n");
            rtxtReceipt.AppendText("Employee Number:" + "\t" + "\t" + txtEmpno.Text + "\n");
            rtxtReceipt.AppendText("Department:" + "\t" + "\t" + "\t" + txtDept.Text + "\n");
            rtxtReceipt.AppendText("Amount to be loaned:" + "\t" + txtAmount.Text + "\n");
            rtxtReceipt.AppendText("Years to Pay:" + "\t" + "\t" + "\t" + txtYears.Text + "\n");
            rtxtReceipt.AppendText("Interest Rate:" + "\t" + "\t" + lblThree.Text + "\n");
            rtxtReceipt.AppendText("Monthly Payment:" + "\t" + "\t" + lblPay.Text + "\n");
            rtxtReceipt.AppendText("Total Payment:" + "\t" + "\t" + lblTot.Text + "\n");
            rtxtReceipt.AppendText("--------------------------------------------------------" + "\t" + "\n");
            rtxtReceipt.AppendText("        Official Receipt of SMEMCO      " + "\n");

        

        public Form1()
        
            InitializeComponent();
        

        private void Form1_Load(object sender, EventArgs e)
        

        
    

在制作数据库时,我观看了一个 youtube 视频。我一步一步地跟着它,但我收到了错误。我也尝试在变量中加入“+”,但也没有用。我的计划是当用户单击添加按钮时,输入的数据和计算将存储到我的数据库表中。相反,该错误弹出。我做错了什么?

错误信息:

【问题讨论】:

我相信带有空格的列名将是一个问题,除非你引用它们......比如“总付款”或[总付款]。仅供参考,不建议您在 DB 字段定义中使用空格,这是原因之一。 不要在列名/sql 参数中使用空格。 (直到您需要并学习如何[使用它们]) 感谢@JohnG 和瑞克。我删除了空格并将 Id 的 Identity 规范设置为 true。 @LeyonCennedy,很高兴听到您的问题已经解决,您可以发布答案并点击'✔'将您的回复标记为答案,这可以帮助其他人解决类似问题. 一些不相关的提示:SqlConnectionSqlCommand 都是IDisposable 所以应该在using 块内。您可能想阅读can we stop using AddWithValue。 【参考方案1】:

不要在列名/sql 参数中使用空格。您也可以尝试将数据库的Id参数的Identity规范设置为true。

【讨论】:

以上是关于SqlException:“nvarchar”附近的语法不正确的主要内容,如果未能解决你的问题,请参考以下文章

错误:System.Data.SqlClient.SqlException(0x80131904):转换 nvarchar 值时转换失败 [关闭]

我的 SqlException 的原因是啥:'=' 附近的语法不正确? [关闭]

例外是 System.Data.SqlClient.SqlException:'9988' 附近的语法不正确 [关闭]

System.Data.SqlClient.SqlException (0x80131904): ')' 附近的语法不正确

为啥我的 JDBC SQLite 数据库中的“@”附近出现 java.sql.SQLException?

System.Data.SqlClient.SqlException:关键字“FROM”附近的语法不正确