Run query in Access from C #

2

I have the following code in C # that I use to consult information from a database in Access:

public DataTable selcfecharegitro()
{
    DataTable dt = new DataTable();
    OleDbDataAdapter da = new OleDbDataAdapter();
    DataSet ds = new DataSet();
    OleDbConnection cone = new OleDbConnection(cc.conaccess);
    string desde = Convert.ToString(new datosform().dtpdesde.Value.ToShortDateString());     
    string hasta = Convert.ToString(new datosform().dtphasta.Value.ToShortDateString());
    da.SelectCommand = new OleDbCommand("select * from Registro where Fecha_uso  between @desde and @hasta ", cone);
    da.SelectCommand.Parameters.AddWithValue("@desde", desde);
    da.SelectCommand.Parameters.AddWithValue("@hasta", hasta);

    da.Fill(ds);

    dt = ds.Tables[0];

    return dt;
}

It does not show me errors, what happens is that it does not show me the data I ask, it only shows the name of the tables but not the data that is in them.

How can I get the records in the table?

    
asked by use2105 27.01.2017 в 17:30
source

2 answers

2

In Access, use the sign of # to mark literal dates, the idea is this:

SELECT * FROM Registro WHERE Fecha_Uso Between #@desde# And #@hasta#;

To make it work:

string desde = "#"+ Convert.ToString(new datosform().dtpdesde.Value.ToShortDateString()) + "#";     
string hasta = "#" Convert.ToString(new datosform().dtphasta.Value.ToShortDateString()) + "#";

Update

We receive the values:

string desde = Convert.ToString(new datosform().dtpdesde.Value.ToShortDateString());     
string hasta = Convert.ToString(new datosform().dtphasta.Value.ToShortDateString());

The query:

SELECT * FROM Registro WHERE Fecha_Uso >= ? And Fecha_Uso <= ?;

Your parameters:

da.SelectCommand.Parameters.AddWithValue("?", desde);
da.SelectCommand.Parameters.AddWithValue("?", hasta);
    
answered by 27.01.2017 в 17:38
0

What I meant by my comments is seen in the following code.

public DataTable selcfecharegitro() {
    DataTable dt = new DataTable();
    OleDbDataAdapter da = new OleDbDataAdapter();
    DataSet ds = new DataSet();
    OleDbConnection cone = new OleDbConnection(cc.conaccess);
    da.SelectCommand = new OleDbCommand("select * from Registro where Fecha_uso  between ? and ? ", cone);
    da.SelectCommand.Parameters.AddWithValue("@desde", fecha_desde_en_datetime);
    da.SelectCommand.Parameters.AddWithValue("@hasta", fecha_hasta_datetime);

    da.Fill(ds);

    dt = ds.Tables[0];

    return dt; }
    
answered by 27.01.2017 в 18:23