我正在设计一个计划器,单击添加任务按钮时遇到问题。单击它后,程序崩溃,并显示此错误:
“ System.Data.SqlClient.SqlException:'关键字'table'附近的语法不正确。'”
在哪里可以找到错误的语法?
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 InfoHub
{
public partial class Planner : Form
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\epoch\source\repos\InfoHub\InfoHub\planner.mdf;Integrated Security=True;Connect Timeout=30");
public Planner()
{
InitializeComponent();
}
private void Planner_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void addTask_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
}
答案 0 :(得分:0)
您使用的sql插入命令不正确:
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
table是sql关键字,不被视为表名。尝试添加将其写为“表”以通知sql,“表”是特定表的名称而不是关键字:
cmd.CommandText = "insert into 'table' values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
通常,总是在“”中写名称是一种好习惯。