"字符串后面的未闭合引号"错误

时间:2017-02-13 20:02:00

标签: c# asp.net asp.net-mvc asp.net-mvc-4

  

' /'中的服务器错误应用

     

' B'附近的语法错误。字符后面有未闭合的引号   字符串',e)'。

     

描述:发生了未处理的异常。

     

异常详细信息:System.Data.SqlClient.SqlException:不正确   语法附近' B'。字符串后面的未闭合引号   ',E)'

     

来源错误:

     

执行期间生成了未处理的异常   当前的网络请求。有关的来源和位置的信息   可以使用下面的异常堆栈跟踪来识别异常。

     

堆栈追踪:

     

[SqlException(0x80131904):' B'附近的语法不正确。未关闭的   字符串后的引号',e)'。]
  System.Data.SqlClient.SqlConnection.OnError(SqlException异常,   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,布尔& dataReady)+4927
  System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(字符串   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   上传)在C:\ Users \ M1037515 \ Documents \ Visual Studio中   2015 \项目\ HalcytronicsInc \ HalcytronicsInc \控制器\ ExcellUploadController.cs:94   lambda_method(Closure,ControllerBase,Object [])+139
  System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext   controllerContext,IDictionary' 2参数)+229
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext   controllerContext,ActionDescriptor actionDescriptor,IDictionary' 2   参数)+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();
        }
    }
}

2 个答案:

答案 0 :(得分:4)

您应该使用参数化查询来避免由拼写错误引起的Sql Injection hacks和简单的语法错误(因为您忘记在许多字符串值周围添加适当的引号)。 如果您的任何值包含单引号,参数也可以避免出现问题。

....
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]);

答案 1 :(得分:1)

正如其他人所说,像这样连接SQL是一种糟糕的形式。话虽这么说,你的错误的原因是在“城市”附近缺少单引号。即使此代码的每个方面都在您的控制之下,您也应该使用参数化查询。

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

应该是:

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