System.Data.SqlClient.SqlException: 'Incorrect syntax near '-'.'

Aishwarya shingre 21 Reputation points
2022-03-03T07:53:44.567+00:00

I am trying to make a simple website that gets your registration details and stores it in a sql database
But I am getting a error saying

System.Data.SqlClient.SqlException: 'Incorrect syntax near '-'.'

Here is my code:

using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections.Generic;

namespace ARTIst_Sketch_Work
{
public partial class Registeration : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Register.mdf;Integrated Security=True");

    protected void Page_Load(object sender, EventArgs e)
    {

    }



    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into [Table] (Username,E-mail,Age,Gender,PhoneNo,Address,Password,ConfirmPassword) values('" + TextBox.Text + "', '" + TextBoxEmail.Text + "', '" + TextBoxAge.Text + "', '" + DD_Gender.Text + "', '" + TextBoxPhone.Text + "', '" + TextBoxAddress.Text + "', '" + TextBoxPa.Text + "', '" + TextBoxCpass.Text + "');";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();


    }

}

}

The exception pops at :

cmd.ExecuteNonQuery();

Any help will be appreciated

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,112 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,519 questions
{count} votes

Accepted answer
  1. Olaf Helper 42,571 Reputation points
    2022-03-03T08:02:30.353+00:00

    System.Data.SqlClient.SqlException: 'Incorrect syntax near '-'.'

    You create the SQL statement dynamically with user entry; a more then a very bad idea, because it allows SQL Injection and also such error caused by user entry.
    Always use parameterized query, then you issues solves itself.

    https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=dotnet-plat-ext-6.0
    https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types

    0 comments No comments

0 additional answers

Sort by: Most helpful