'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Dejvi Mehdi 21 Reputation points
2022-12-01T21:57:05.977+00:00

//Here is 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 Projekt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    private void button1_Click(object sender, EventArgs e)  
    {  
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Asus\Documents\DataTest12.mdf;Integrated Security=True;Connect Timeout=30");  
        con.Open();  
        SqlCommand cmd = new SqlCommand("Insert into [Table] values (@ID,@Name,@Age)", con);  
        cmd.Parameters.AddWithValue("@ID", int.Parse(textBox1.Text));  
        cmd.Parameters.AddWithValue("@Name", (textBox2.Text));  
        cmd.Parameters.AddWithValue("@Age", double.Parse(textBox3.Text));  
        cmd.ExecuteNonQuery();  
        con.Close();  
        MessageBox.Show("Succesfully Saved");  


    }  

    private void button2_Click(object sender, EventArgs e)  
    {  
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Asus\Documents\DataTest12.mdf;Integrated Security=True;Connect Timeout=30");  
        con.Open();  
        SqlCommand cmd = new SqlCommand($"Update [Table] set Name=@Name, Age= @Age where ID = @ID)", con);  
        cmd.Parameters.AddWithValue("@ID", int.Parse(textBox1.Text));  
        cmd.Parameters.AddWithValue("@Name", (textBox2.Text));  
        cmd.Parameters.AddWithValue("@Age", double.Parse(textBox3.Text));  
        cmd.ExecuteNonQuery();  
        con.Close();  
        MessageBox.Show("Succesfully Updated");  
    }  
}  

}

Additional information: Incorrect syntax near ')'.
The code stuck on cmd.ExecuteNonQuery();

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,985 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 68,306 Reputation points
    2022-12-01T22:03:09.53+00:00

    in line 20, your sql statement has a trailing ")" which is invalid syntax as suggested by the error message

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.