简体   繁体   English

SqlException未处理,语法错误

[英]SqlException was unhandled, incorrect syntax

I have the following problem when performing a query on sqlserver management: 在sqlserver管理上执行查询时遇到以下问题:

An unhandled exception of type ' System.Data.SqlClient.SqlException ' occurred in System.Data.dll System.Data.dll中发生了类型为'System.Data.SqlClient.SqlException'的未处理的异常

Additional information : Incorrect syntax near ' u' . 附加信息:'u'附近的语法不正确。

The code is as follows: 代码如下:


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;

            }
        }

The function: public static Alumno ObtenerUsuario(String usuarionumero) It comes from: 函数: 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;

               }


           }

How can I resolve this problem? 我该如何解决这个问题?

Appending your parameters directly into command text is a bad practice, you make yourself vulnurable to the SQL injection. 将参数直接附加到命令文本中是一种不好的做法,会使自己容易受到SQL注入的攻击。 You can add your variable usuarionumero as a parameter like this 您可以像这样将变量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 ); 

This should solve your problem by escaping special characters inside usuarionumero in resulting SQL 这应该通过在结果SQL中转义usuarionumero内的特殊字符来解决您的问题

If, for whatever reason, you've decided that you don't want to use parameters as described by Alex Buyny, the actual syntax error with your inline query appears to be that you forgot to add single quotes around the value that you're using in your where clause, like so: 如果由于某种原因,您决定不想使用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);

Notice that I've changed Id={0} to Id='{0}' . 请注意,我已将Id={0}更改为Id='{0}'

However, as Alex mentioned, doing queries this way can lead to SQL injection attacks. 但是,正如Alex所提到的,以这种方式进行查询可能会导致SQL注入攻击。 For instance, consider what happens if someone called your method and passed something like this for usuarionumero : 例如,考虑如果有人调用了您的方法并为usuarionumero传递了类似的内容,会发生什么情况:

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

As you can see, this could lead to disastrous results. 如您所见,这可能会导致灾难性的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM