简体   繁体   中英

Selection using dapper

I have a problem with my query using dapper, whether someone imagine to help me and say where I'm doing the wrong, is currently showing me an error at the date when I put a breik point, how to correct it properly? thank you all for help

this is my current code

public string GetBezeichnung(int LP, DateTime date)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection())
    {
        connection.ConnectionString = _ConnectionString;
        var output = connection.Query<string>("SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = " + LP + " AND ZER_Datum = " + date).FirstOrDefault();
        return output;
    }
}

and this is the result with which I get an error

图像描述在这里

Try parameterizing the query.

public string GetBezeichnung(int LP, DateTime date)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(_ConnectionString))
    {
        connection.Open();
        string sql = @"
SELECT ZER_Bezeichnung 
FROM Z_ERFASSUNG 
WHERE ZER_LPE = @LP
  AND ZER_Datum = @date"
        var output = connection.Query<string>(sql, new { LP = LP, date = date }).FirstOrDefault();
        return output;
    }
}

I agree with @Parrish Husband, but the Second Paramater has to be "Date = date".

In your example there are no ' around the date so AQL thinks its a bunch or things.

Changing it to

var output = connection.Query<string>("SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = " + LP + " AND ZER_Datum = '" + date + "'").FirstOrDefault();

will make it work.

Use the following line of code so that it will match the exact date. if the time for the date is different then it will not fetch that records.

var output = connection.Query<string>("SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = " + LP + " AND Cast( ZER_Datum as DATE) = Cast('" + date + "' as DATE)").FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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