I am currently trying to connect to a database made in MS SQL Server and insert a row when a button on a form is clicked. Below is my code and an explanation of what is going wrong.
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 WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = 'u:\\my documents\\visual studio 2015\\Projects\\WindowsFormsApplication10\\WindowsFormsApplication10\\InventoryDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand myCommand = new SqlCommand("INSERT INTO Table (Barcode, Item, Quantity) Values (123, 'Item 123', 5)", myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
I believe I have connected to the database, because in previous attempts I was getting an error at myConnection.Open(). Now I am getting an error at myCommand.ExecuteNonQuery(); which says:
SqlException was Unhandled: An Unhandled Exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'Table'.
Tableis a keyword. msdn.microsoft.com/en-us/library/ms189822.aspx You can name your tablesTable, but you shouldn't. Then you always have to use brackets to escape it:[Table].SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = 'u:\my documents\visual studio 2015\Projects\WindowsFormsApplication10\WindowsFormsApplication10\InventoryDB.mdf'; Integrated Security = True; Connect Timeout = 30");