0

I want to insert some data in a database that fetches the information to insert from the Form that I created. I am using the following command:

String query = @"INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting) VALUES( " 
                + NameBox.Text.Split(null)[0]+ " , " 
                + SurnameBox.Text.Split(null)[0] + " , " 
                + type + " , " 
                + Convert.ToDouble(idNBox.Text) + " , " 
                + gender + "," + Companybox.Text + " , "
                + delivery + " , " + DateTime.Now + " ," 
                + VisitingCombo.Text 
                + " )";

The table was created with the following structure,

CREATE TABLE [dbo].[Visits] (
[Name]     NVARCHAR (50) NOT NULL,
[Surname]  NVARCHAR (50) NOT NULL,
[DocType]  NVARCHAR (50) NOT NULL,
[IdNumber] BIGINT NOT NULL,
[Gender]   NCHAR (1)     NOT NULL,
[Company]  NVARCHAR (50) NOT NULL,
[Delivery] BIT           NOT NULL,
[Entrance] DATE          NOT NULL,
[Out]      DATE          NULL,
[Visting]  NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([IdNumber] ASC, [DocType] ASC, [Entrance] ASC),
FOREIGN KEY ([Visting]) REFERENCES [dbo].[Person] ([Name]));

When running the code I try to insert the following error appears,

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

For the insertion I used some code that I found in a response by Nicholas Carey that could solve my problem. How to directly execute SQL query in C#? Have example batch file

I know that the error occurs in the very first value of the query. What am I doing wrong in here?

Sunil
  • 3,404
  • 10
  • 23
  • 31

6 Answers6

1

You should not use string concatenation for SQL query building, especially if it's partially received from user input. Please be aware of SQL Injection attack.

Instead use parameterized query:

var cmd = new SqlCommand(@"INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting)
VALUES(@Name,@Surname,@DocType,@DocNumber,@Gender,@Company,@Delivery,@Entrance,@Visiting)", yourDbConnection);

cmd.Parameters.Add(new SqlParameter("@Name", NameBox.Text.Split(null)[0]));
//... Add other parameters in the same way

cmd.ExecuteNonQuery();

PS: Your direct problem is missing quotes around string values probably, but DO NOT concatenate that in any case!

Sasha
  • 8,537
  • 4
  • 49
  • 76
1

its very bad solution.

it can be hack.

its better use ADO.NET

 using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionCS"].ConnectionString))
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting) VALUES(@Name,@Surname,@DocType,@DocNumber,@Gender,@Company,@Delivery,@Entrance,@Visiting)");
        using (SqlCommand com = new SqlCommand(sb.ToString(), con))
        {
            con.Open();
            com.Parameters.Add("@Name", SqlDbType.NVarChar).Value = NameBox.Text.Split(null)[0];
            //Add Other Parameter
            //...
            com.ExecuteScalar();
        }
    }
mhsankar
  • 423
  • 5
  • 18
1

Short Answer

In your query, you missed to put the string (varchar) values in quotes '.

Example:

String query = @"INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting) VALUES( " 
               + "'" + NameBox.Text.Split(null)[0]+ "' , " 

Better Answer:

You query suffer from SQL injection attack and maintainability issue. You should consider parameterizing your query to avoid them.

Example:

String query = @"INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting) VALUES( " 
               + "@Name, " ...

command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = NameBox.Text; 

Remaining parameters is left for you to practice and learn.

Sunil
  • 3,404
  • 10
  • 23
  • 31
0

i would suggest you to check the quotation marks are proper or not use single quote inside double quote , put a debugger on the String query variable & then check what the variable contains is it having a proper query or not , & change as per the error in the varible value

imdisney
  • 109
  • 1
  • 13
0

Long queries tend to get really messy really quickly. As Oleksandr said the way that you are passing information into an INSERT query is pretty dangerous. Try something like this :

string query = "INSERT INTO Visits(Name,Surname,DocType,DocNumber,Gender,Company,Delivery,Entrance,Visiting) VALUES(@name, @surname, @docType, @docNumber, @gender, @company, @delivery, @entrance, @visiting)";
string param = new {@name = NameBox.Text, @surname = SurnameBox.Text, ... @visiting = VisitingCombo.Text};

This means that any information that is passed to your database is passed as string, instead of someone being able to pass through unwanted SQL queries.

The reason you were getting a syntax exception is most likely because if you are passing straight text to a query you must wrap it in 'single quotes' .

Paramaterising your input both protects you from SQL Injection/Poisoning and avoids issues relating to data type declaration in your query.

ddaannnnyy
  • 101
  • 5
0

Please use stored procedure to solve this type of error. It is also fast while saving the data into data base.

pankaj singh
  • 95
  • 10