-1

Server Error in '/' Application.

Incorrect syntax near 'B'. Unclosed quotation mark after the character string ',e)'.

Description: An unhandled exception occurred.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'B'. Unclosed quotation mark after the character string ',e)'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): Incorrect syntax near 'B'. Unclosed quotation mark after the character string ',e)'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action'1 wrapCloseInAction) +3278868
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +791
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1275
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource'1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +367
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +386
HalcytronicsInc.Controllers.ExcellUploadController.Upload(HttpPostedFileBase upload) in C:\Users\M1037515\Documents\Visual Studio 2015\Projects\HalcytronicsInc\HalcytronicsInc\Controllers\ExcellUploadController.cs:94 lambda_method(Closure , ControllerBase , Object[] ) +139
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary'2 parameters) +229
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary'2 parameters) +35
System.Web.Mvc.<>c__DisplayClass15.b__12() +80 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func'1 continuation) +453
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func'1 continuation) +453
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +533

using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HalcytronicsInc.Models;
using System.Data.SqlClient;

namespace HalcytronicsInc.Controllers
{
    public class ExcellUploadController : Controller
    {
        public string country;
        public string state;
        public string city;
        public string name;
        public string pno;
        // GET: ExcellUpload
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult Upload(HttpPostedFileBase upload)
        {

            if (ModelState.IsValid)
            {

                if (upload != null && upload.ContentLength > 0)
                {
                    // ExcelDataReader works with the binary Excel file, so it needs a FileStream
                    // to get started. This is how we avoid dependencies on ACE or Interop:
                    Stream stream = upload.InputStream;

                    // We return the interface, so that
                    IExcelDataReader reader = null;


                    if (upload.FileName.EndsWith(".xls"))
                    {
                        reader = ExcelReaderFactory.CreateBinaryReader(stream);
                    }
                    else if (upload.FileName.EndsWith(".xlsx"))
                    {
                        reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    }
                    else
                    {
                        ModelState.AddModelError("File", "This file format is not supported");
                        return View();
                    }

                    reader.IsFirstRowAsColumnNames = true;

                    DataSet result = reader.AsDataSet();
                    // string connectionString = null;
                    SqlConnection connection;
                    SqlCommand command;
                    SqlDataAdapter adpter = new SqlDataAdapter();

                    connection= new SqlConnection(/*"Data Source=A2ML10582;User ID =sa;Password =****************;Integrated Security = true"*/
                        "Data Source=A2ML10582;Initial Catalog=HalcytronicsINCSitecore_Master;User ID=sa;Password=****************"
                        );
                    //connectionString = "Data Source = 172.17.2.13; Initial Catalog ="User ID = sa Password = ***********"  Integrated Security = true";

                    //connection = new SqlConnection(connectionString);

                    int i = 0;
                    connection.Open();
                    for (i = 0; i <= result.Tables[0].Rows.Count - 1; i++)
                    {
                        country = result.Tables[0].Rows[i].ItemArray[0].ToString();
                        state = result.Tables[0].Rows[i].ItemArray[1].ToString();
                        city =result.Tables[0].Rows[i].ItemArray[2].ToString();
                        name = result.Tables[0].Rows[i].ItemArray[3].ToString();
                        pno = result.Tables[0].Rows[i].ItemArray[4].ToString();
                        string sql = "insert into SalesRepresentative(" + country + ",'" + state + "'," + city + "','+" + name + "'," + pno + ")";
                        command = new SqlCommand(sql, connection);
                        adpter.InsertCommand = command;
                        adpter.InsertCommand.ExecuteNonQuery();
                    }
                    connection.Close();

                    reader.Close();

                    return View(result.Tables[0]);
                }
                else
                {
                    ModelState.AddModelError("File", "Please Upload Your file");
                }
            }
            return View();
        }
    }
}
Andrew
  • 7,602
  • 2
  • 34
  • 42
  • 5
    Do not concatenate strings to form sql command. Use parameters instead. Your string is full of errors. – Steve Feb 13 '17 at 20:05
  • 2
    If you have to add "help me" in the title of the question because your question title is a duplicate maybe you should just check the duplicate question. – takendarkk Feb 13 '17 at 20:18
  • `," + city + "'` you never opened the single quote on city, but you closed it, so there is an odd number of single quotes, plus the quotes make the rest of the insert garbage. Seriously don't concatenate strings like that for an insert statement, or any sql statement really. – Andrew Feb 13 '17 at 20:30
  • [Please read this](http://stackoverflow.com/help/how-to-ask) – Andrew Feb 13 '17 at 20:36

2 Answers2

4

You should use a parameterized query to avoid Sql Injection hacks and simple syntax errors caused by typos (as you have here in forgetting to add proper quotes around many strings values).
Also a parameters avoid problems if any of your values contains a single quote.

....
DataSet result = reader.AsDataSet();

string cmdText = @"insert into SalesRepresentative
    (@country,@state,@city,@name,@pno)";

// using statement around disposable objects.....
using(SqlConnection connection= new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, connection))
{
    connection.Open();

    // Add all parameters before entering the insert loop        
    cmd.Parameters.Add("@country", SqlDbType.NVarChar);
    cmd.Parameters.Add("@state", SqlDbType.NVarChar);
    cmd.Parameters.Add("@city", SqlDbType.NVarChar);
    cmd.Parameters.Add("@name", SqlDbType.NVarChar);
    cmd.Parameters.Add("@pno", SqlDbType.NVarChar);


    for (i = 0; i < result.Tables[0].Rows.Count; i++)
    {
        country = result.Tables[0].Rows[i].ItemArray[0].ToString();
        state = result.Tables[0].Rows[i].ItemArray[1].ToString();
        city =result.Tables[0].Rows[i].ItemArray[2].ToString();
        name = result.Tables[0].Rows[i].ItemArray[3].ToString();
        pno = result.Tables[0].Rows[i].ItemArray[4].ToString();

        // Set the parameter values 
        cmd.Parameters["@country"].Value = country;
        cmd.Parameters["@state"].Value = state;
        cmd.Parameters["@city"].Value = city ;
        cmd.Parameters["@name"].Value = name;
        cmd.Parameters["@pno"].Value = pno;

        // No need of an SqlDataAdapter here, just execute the command...
        cmd.ExecuteNonQuery();
   }
}
return View(result.Tables[0]);
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Server Error in '/' Application. ExecuteNonQuery requires an open and available Connection. The connection's current state is closed. – Srk_Babre_1994 Feb 14 '17 at 05:00
  • Initially I had forgotten the _connection.Open_ line. Strange, I have added it 10 hours ago probably you need to just refresh the page., – Steve Feb 14 '17 at 06:45
1

As others have stated, concatenating SQL like this is poor form. That being said, the cause of your error is a missing single quote near "city". Even if every aspect of this code is under your control, you should be using paramaterized queries.

string sql = "insert into SalesRepresentative(" + country + ",'" + state + "'," + city + "','+" + name + "'," + pno + ")";

Should be:

string sql = "insert into SalesRepresentative(" + country + ",'" + state + "','" + city + "','+" + name + "'," + pno + ")";
Forklift
  • 949
  • 8
  • 20
  • 1
    Stack Overflow is a reference tool for millions of people, and our answers are learning opportunities for everyone. Not making the OP aware of the dangers of your code, or taking the time to teach the OP why this is dangerous is a missed opportunity in my opinion. – maccettura Feb 13 '17 at 20:11