首页 > 解决方案 > 如何使用 where 使这个 SQL 语句工作

问题描述

我有以下代码,我想用 where 语句进行查询,但它没有给我任何结果,你能帮我吗

public List<Persona> Listarwhere()
{
    List<Persona> oLista = new List<Persona>();

    using (SQLiteConnection conexion = new SQLiteConnection(cadena))
    {
        conexion.Open();

        Persona obj = new Persona();
        Form1 idcliente = new Form1();
        //int cliente = int.Parse(idcliente.txtidpersona.Text);

        string query = "select IdPersona, Nombre, Apellido, Telefono from Persona where idpersona = @idpersona";

        SQLiteCommand cmd = new SQLiteCommand(query, conexion);
        cmd.Parameters.Add(new SQLiteParameter("@idpersona", idcliente.txtidpersona.Text));
        cmd.CommandType = System.Data.CommandType.Text;

        using (SQLiteDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                oLista.Add(new Persona()
                    {
                        IdPersona = int.Parse(dr["IdPersona"].ToString()),
                        Nombre = dr["Nombre"].ToString(),
                        Apellido = dr["Apellido"].ToString(),
                        Telefono = dr["Telefono"].ToString()
                    });
            }
        }
    }

    return oLista;
}

我需要在几个文本框中传递这个查询的数据

标签: c#winformssqlite

解决方案


您应该尝试将您的“idpersona”作为参数传递给您的方法。...也许是这样的:

public List<Persona> Listarwhere(string id) // or (int id)
{
    List<Persona> oLista = new List<Persona>();

    using (SQLiteConnection conexion = new SQLiteConnection(cadena))
    {
        conexion.Open();

        Persona obj = new Persona();
        //Form1 idcliente = new Form1();
        //int cliente = int.Parse(idcliente.txtidpersona.Text);

        string query = "select IdPersona, Nombre, Apellido, Telefono from Persona where idpersona = @idpersona";

        SQLiteCommand cmd = new SQLiteCommand(query, conexion);
        cmd.Parameters.Add(new SQLiteParameter("@idpersona", id));
        cmd.CommandType = System.Data.CommandType.Text;

        using (SQLiteDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                oLista.Add(new Persona()
                    {
                        IdPersona = int.Parse(dr["IdPersona"].ToString()),
                        Nombre = dr["Nombre"].ToString(),
                        Apellido = dr["Apellido"].ToString(),
                        Telefono = dr["Telefono"].ToString()
                    });
            }
        }
    }

    return oLista;
}

推荐阅读