【问题标题】:Exception : The length of the parameter exceeds the limit of 128 characters in C#异常:参数长度超过 C# 中 128 个字符的限制
【发布时间】:2015-03-25 11:00:03
【问题描述】:

我正在尝试使用 WCF 服务在 SQLServer 中插入值。 有 5 行要插入。

它的例外:

参数长度超过128个字符的限制

是的,它的长度超过 128 个字符。但我已经声明了大小 NVarChar(4000)。

我已经搜索了这个网站和其他网站以了解并摆脱这个异常

MedicineTestName = "1,crocin,2,aspirin,2,naproxen,3,ibuprofen,3,Ketaprofen";

代码:

public static string InsertHistory(string PatientId, string MedicineTestName, string CreateBy)
    {
       DataSet objdata;
       object objSubjectReader = new object();
        try
        {
               StringBuilder sb = new StringBuilder();

            string[] wordswithcomma = MedicineTestName.Split(',');

            for (int i = 0; i < wordswithcomma.Length -1 ; i=i+2)
            {

                string MedicineType = wordswithcomma[i];
                string MedicineName = wordswithcomma[i + 1];

                sb.Append("insert into tblMedicineHistory values(" + PatientId + "," + "'" + MedicineName + "'" + "," + MedicineType + ",GETDATE()," + "'" + CreateBy + "'" + ",GETDATE(),0);");

            }
            string sbo = sb.ToString();

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter(sbo, System.Data.SqlDbType.NVarChar, 4000);
            param[0].Value = sbo;

           objdata = SqlHelper.ExecuteDataset(ConString, CommandType.StoredProcedure, "SP_MedicineHistory", param);


           return JsonConvert.SerializeObject(objdata, Newtonsoft.Json.Formatting.Indented);
            //return sbo;
        }
        catch (SqlException ex)
        {

            return objSubjectReader.ToString();
        }

    }

谢谢。

【问题讨论】:

  • 我在这里很害怕;根据显示的代码,您应该在医疗系统上工作...

标签: c# sql-server wcf exception


【解决方案1】:

我认为是在抱怨参数的名称;您将sbo 作为参数名称传递,但sbo完全组合的TSQL,它将是...长。注意:您的 SQL 完全不安全 - 不是如何参数化 SQL!

正确参数化单行的 SQL 将类似于:

const string sql = @"
insert into tblMedicineHistory (PatientID, MedicineName, MedicineType, ...)
values(@patientId, @medicineName, @medicineType, ...)";

var args = new[] {
    new SqlParameter("@patientId", PatientId),
    new SqlParameter("@medicineName", MedicineName),
    new SqlParameter("@medicineType", MedicineType),
    ...
}

【讨论】:

  • 谢谢你,两个答案都很有帮助,我是新手。你能提供任何链接来正确学习。
  • @SClearner 实际上,一个很好的起点可能是my other answer from this morning - 从中​​您还可以了解到半令人欣慰的事实:错误并不少见;p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2018-09-30
  • 1970-01-01
  • 2014-09-12
相关资源
最近更新 更多