Defus Defus - 5 months ago 121
SQL Question

VisualStudio error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

When trying to insert the following information into my database I get "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

My code

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");

}
}
}


Here is the error
cmd.ExecuteNonQuery();


Full Exception details

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:

Answer

Your immediate error is because you are using the keyword Table. Instead use [Table].

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

After that, you should start looking into query parameterization in order to prevent sql injection and to help with debugging and extendability.