【问题标题】:SqlException was unhandled, incorrect syntaxSqlException 未处理,语法不正确
【发布时间】:2015-05-15 00:48:05
【问题描述】:

我在sqlserver管理上执行查询时遇到以下问题:

System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常

附加信息:“u”附近的语法不正确。

代码如下:


public static Alumno ObtenerUsuario(String usuarionumero)
        {
            //long Id_int;
            //Id_int = Convert.ToInt64(pId);
            using (SqlConnection conexion = BDComun.ObtnerCOnexion())
            {

                Alumno pAl = new Alumno();
                SqlCommand comando = new SqlCommand(String.Format("Select Id, Nombre, Apellido, Usuario, Cargo, Celular, rfid, Fecha_Nac, Estado, Check_acceso, Empresa_contratista from Alumnos where Id={0}", usuarionumero), conexion);

                SqlDataReader reader = comando.ExecuteReader();

                while (reader.Read())
                {
                    pAl.Nombre = reader.GetString(1);
                    pAl.Apellido = reader.GetString(2);
                    pAl.Usuario = reader.GetString(3);
                    pAl.Cargo = reader.GetString(4);
                    pAl.Celular = reader.GetString(5);
                    //pAl.rfid = reader.GetString(6);
                    pAl.Fecha_Nac = reader.GetString(7);
                    pAl.Estado = reader.GetString(8);
                    pAl.Check_acceso = reader.GetString(9);
                    pAl.Empresa_contratista = reader.GetString(10);
                }
                conexion.Close();
                return pAl;

            }
        }

函数:public static Alumno ObtenerUsuario(String usuarionumero) 它来自:

public static Alumno ObtenerUsuario(string prfid)
       {
           int dato_numerico;
           int informacion_de_estado_2 = 0;
           while (prfid.Contains(""))
           {
               prfid = "123456789012";

           }
           while (prfid.Contains(""))
           {
               prfid = "123456789012";
           }
           while (prfid.Contains("~"))
           {
               prfid = "123456789012";  
               informacion_de_estado_2 = 1; // 1 = Acceso Denegado 0 = Acceso permitido para el registro
           }
           while (prfid.Contains("¢")) //¢
           {
               prfid = "123456789012";  
               informacion_de_estado_2 = 1; // 1 = Acceso Denegado 0 = Acceso permitido para el registro
           }
           
               using (SqlConnection conexion = BDComun.ObtnerCOnexion())
               {

                   Alumno pAlumno = new Alumno();


                   SqlCommand comando = new SqlCommand(string.Format(
                       "Select Id, Nombre,  Apellido, Usuario, Cargo, Celular, rfid, Fecha_Nac, Empresa_contratista from Alumnos where rfid = {0}", prfid), conexion);
                    
                   ////try
                   ////{
                       SqlDataReader reader = comando.ExecuteReader();

                   //}
                   //catch (Exception exp)
                   //{
                   //    //  MessageBox.Show("Por favor inicia registros para habilitar el control.", "Iniciar registros", MessageBoxButtons.OK, MessageBoxIcon.Information);
                   //}
                  
                   while (reader.Read())
                   {
                       pAlumno.Id = reader.GetString(0);
                       pAlumno.Nombre = reader.GetString(1);
                       pAlumno.Apellido = reader.GetString(2);
                       pAlumno.Usuario = reader.GetString(3);
                       pAlumno.Cargo = reader.GetString(4);
                       pAlumno.Celular = reader.GetString(5);
                       pAlumno.rfid = reader.GetString(6);
                       pAlumno.Fecha_Nac = reader.GetString(7);
                       pAlumno.Empresa_contratista = reader.GetString(8);
                       // pAlumno.Fecha_Nac = Convert.ToString(reader.GetDateTime(7));

                   }
                    
                   conexion.Close();
                   return pAlumno;

               }

        
           }

我该如何解决这个问题?

【问题讨论】:

  • 你得到堆栈跟踪了吗?
  • 出现错误时变量usuarionumero的值是多少?

标签: c# sql-server


【解决方案1】:

将参数直接附加到命令文本中是一种不好的做法,会使自己容易受到 SQL 注入的影响。 您可以像这样将变量 usuarionumero 添加为参数

SqlCommand comando = new SqlCommand("Select Id, Nombre, Apellido, Usuario, Cargo, Celular, rfid, Fecha_Nac, Estado, Check_acceso, Empresa_contratista from Alumnos where Id=@Id");
cmd.Parameters.AddWithValue("@id", usuarionumero ); 

这应该可以通过在生成的 SQL 中转义 usuarionumero 中的特殊字符来解决您的问题

【讨论】:

    【解决方案2】:

    如果出于某种原因,您决定不想使用 Alex Buyny 所描述的参数,则内联查询的实际语法错误似乎是您忘记在值周围添加单引号您在 where 子句中使用,如下所示:

                    SqlCommand comando = new SqlCommand(String.Format("Select Id, Nombre, Apellido, Usuario, Cargo, Celular, rfid, Fecha_Nac, Estado, Check_acceso, Empresa_contratista from Alumnos where Id='{0}'", usuarionumero), conexion);
    

    请注意,我已将 Id={0} 更改为 Id='{0}'

    但是,正如 Alex 所提到的,以这种方式进行查询可能会导致 SQL 注入攻击。例如,考虑一下如果有人调用您的方法并为usuarionumero 传递类似的内容会发生什么:

    null'; drop table Alumnos where '1' = '1
    

    如您所见,这可能会导致灾难性的后果。

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2019-11-29
      • 2021-01-23
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多