将数组插入SQL Server数据库问题

| 我正在尝试将数组插入SQL Server数据库。收到错误之前,将1/4复制到数据库:   \'s \'附近的语法不正确。未封闭   字符后的引号   字符串\',\')\'。 这是按钮点击事件-
private void button3_Click(object sender, EventArgs e)
{
   SqlConnection sql = new SqlConnection(\"server=localhost; uid=xxxx; pwd=xxxx; database=Movies;\");
   sql.Open();

   for (int i = 0; i < jointArray.Length; i++)
   {
      SqlCommand command = new SqlCommand(\"insert into [\" + folderName + \"] \" + \"values(\'\" + jointArray[i].ToString() +\"\', \'\')\", sql);
      command.ExecuteNonQuery();
   }

   sql.Close();
}
    
已邀请:
        我可能会猜测,通过jointArray [i] .ToString()的1/4方式中包含撇号。 因此,而不是像这样的SQL查询。
insert into [MyFolder] values(\'MyValue\')
你最终得到的东西看起来像这样
insert into [MyFolder] values(\'MyValue\'s\')
这会导致错误(请注意s附近语法错误的地方!) 请考虑在SQLCommand中使用参数(查找look3ѭ和
Parameters.AddWithValue
)。 使用参数使您的代码 更具可读性 更容易调试 不太容易受到SQL注入攻击(最近遭到Sony Pictures黑客攻击)     
        看起来您的数据中可能带有撇号,这使查询变得混乱。 这是一个非常糟糕的方法。除非可以保证您的数据不会包含任何意外字符,否则至少应使用SQL参数以确保正确解释它们。     
        您的数组元素之一很可能包含撇号。     
        问题是您没有正确地将字符串编码为SQL中的字符串文字。当字符串中有撇号时,它将破坏语法。 您应该使用参数,而不是将字符串连接到SQL代码中。 这也将允许您对所有查询重用相同的查询和命令对象,而不是为每个查询创建新的命令。您还可以在循环之前在命令上调用
Prepare
,以减少每次执行的一些开销。 例:
private void button3_Click(object sender, EventArgs e) {

  using (SqlConnection sql = new SqlConnection(\"server=localhost; uid=xxxx; pwd=xxxx; database=Movies;\")) {
    sql.Open();

    using (SqlCommand command = new SqlCommand(\"insert into [\" + folderName + \"] values(@P, \'\')\", sql) {

      SqlParameter param = command.Parameters.Add(\"@P\", SqlDbType.VarChar, 50);
      command.Prepare();

      for (int i = 0; i < jointArray.Length; i++) {
        param.Value = jointArray[i].ToString();
        command.ExecuteNonQuery();
      }

    }
  }
}
    
        签出SQL转义字符,例如ѭ7     
        在您的值的某个位置,您有不转义的单引号。这样的问题应该可以快速解决。
SqlCommand command = new SqlCommand(\"insert into [\" + folderName + \"] \" + \"values(\'\" + jointArray[i].ToString().Replace(\"\'\", \"\'\'\") +\"\', \'\')\", sql);
编辑 糟糕,粘贴错误!粘贴您所拥有的。     

要回复问题请先登录注册