【问题标题】:SQL. Incorrect syntax near the keywordSQL。关键字附近的语法不正确
【发布时间】:2020-06-25 13:01:23
【问题描述】:

如何解决这些错误?

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.SqlClient;

namespace Adatbázis_kezelés
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Test.mdf;Integrated Security=True;Connect Timeout=30");
        private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            String query = "insert into Table (id,Name,Fname,Age,Gender,Addres) VALUES('"+textBox1.Text+ "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + comboBox1.Text + "','" + textBox5.Text + "')";
            SqlDataAdapter SDA = new SqlDataAdapter(query, con);
            SDA.SelectCommand.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("INSTERTION SUCCESSFULLY !!!");
        }
    }
}

【问题讨论】:

  • 您没有发布图片。最好将错误消息以文本形式发布(以便可搜索)。
  • 您的代码对SQL injections开放。例如,如果您的 id 列是数字,那么第一个参数周围的单引号是错误的。
  • 错误消息是文本,为了将来参考,习惯上将消息作为文本放在问题中。至于错误,您的 sql 中有一个语法错误,这在您通过连接字符串构建 sql 时很常见。使用参数不仅可以防止 sql 注入,还有助于避免语法错误。
  • 转义table:insert into [Table] ...

标签: c# sql syntax


【解决方案1】:

由于Table 是 SQL 中的保留字,您应该将其括在括号中。

INSERT INTO [Table] ...

【讨论】:

  • 感谢您的帮助,它的工作。祝你有美好的一天:D
猜你喜欢
  • 2016-06-08
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多