Advertisements
I am new to C#. I am trying to make a simple form with 3 buttons.
- 1st button inserts new items (This works)
- 2nd button updates existing data (This doesn’t work)
- 3rd button deletes records (This works)
When I click the 2nd button, I get this error message:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
I can’t figure out where the problem is…
Here’s my code:
namespace MSSQL_CONN_STRING_PRCTC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void INSERT_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = ENGINE\\SQLEXPRESS; Initial Catalog = HORVKAR85; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand("Insert into T_PERSON values (@NAME,@AGE,@BIRTH_PLACE)", con);
cmd.Parameters.AddWithValue("@NAME", textBox2.Text);
cmd.Parameters.AddWithValue("@AGE", int.Parse(textBox3.Text));
cmd.Parameters.AddWithValue("@BIRTH_PLACE", textBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item inserted");
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = ENGINE\\SQLEXPRESS; Initial Catalog = HORVKAR85; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand("Update T_PERSON set NAME=@NAME, AGE=@AGE, BIRTH_PLACE=@BIRTH_PLACE where T_PERSON_ID = @T_PERSON_ID)", con);
cmd.Parameters.AddWithValue("@T_PERSON_ID", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("@NAME", textBox2.Text);
cmd.Parameters.AddWithValue("@AGE", int.Parse(textBox3.Text));
cmd.Parameters.AddWithValue("@BIRTH_PLACE", textBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item Updated");
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = ENGINE\\SQLEXPRESS; Initial Catalog = HORVKAR85; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand("Delete From T_PERSON where T_PERSON_ID = @T_PERSON_ID", con);
cmd.Parameters.AddWithValue("@T_PERSON_ID", int.Parse(textBox1.Text));
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item Deleted");
}
}
}
My includes are:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
What did I do wrong? Thanks in advance.
I tried to find a solution by reading a few articles, but to no avail…
>Solution :
I think you are making a very simple mistake
Update T_PERSON set NAME=@NAME, AGE=@AGE, BIRTH_PLACE=@BIRTH_PLACE
Where T_PERSON_ID = @T_PERSON_ID)
^
_________________________________|
Remove the parenthesis at the end of the update statement. Change like below and it should work.
Update T_PERSON set NAME=@NAME, AGE=@AGE, BIRTH_PLACE=@BIRTH_PLACE
Where T_PERSON_ID = @T_PERSON_ID
^
___ no parenth __________________|