VisualStudio错误:System.Data.dll中发生未处理的“System.Data.SqlClient.SqlException”类型异常

时间:2016-06-17 12:27:16

标签: c# mysql

当我尝试将以下信息插入到我的数据库中时,我得到“System.Data.dll中出现类型'System.Data.SqlClient.SqlException'的异常

我的代码

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 wsiz
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\rf\Documents\wsiz.mdf;Integrated Security=True;Connect Timeout=30");
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO Table (imie,nazwisko,miasto) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text +"');";
            cmd.ExecuteNonQuery();
            con.Close();

            MessageBox.Show("record inserted successfully");

        }
    }
}

这是错误cmd.ExecuteNonQuery();

完整例外详情

System.Data.SqlClient.SqlException occurred
  Class=15
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=1
  Message=Incorrect syntax near the keyword 'Table'.
  Number=156
  Procedure=""
  Server=(LocalDB)\MSSQLLocalDB
  Source=.Net SqlClient Data Provider
  State=1
  StackTrace:
       w System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       w System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       w System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       w System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       w System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
       w System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       w System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       w wsiz.Form1.button1_Click(Object sender, EventArgs e) w c:\users\rf\documents\visual studio 2015\Projects\wsiz\wsiz\Form1.cs:wiersz 28
  InnerException:

1 个答案:

答案 0 :(得分:3)

您的即时错误是因为您使用的是关键字Table。而是使用[Table]

"INSERT INTO [Table] (imie,nazwisko,miasto) VALUES ..."

之后,您应该开始研究查询参数化,以防止sql注入并帮助调试和扩展。