使用带参数的查询从 table 获取数据时出现问题

Troubles when fetching data from table with a query with a parameter

我正在与 ASP.net 合作。我正在尝试从 table“Pret”中获取数据并将其显示在视图中。以下代码运行正常:

public ActionResult Details(int id)
{
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection con = new SqlConnection(chaineConnexion))
    {
        DataTable tabRetard = new DataTable();
        con.Open();

        SqlDataAdapter adp = new SqlDataAdapter();

        SqlCommand command = new SqlCommand(
            "SELECT Livre.titre,Membre.nom, " +
                "FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
                "LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
                "LEFT JOIN Membre ON Retard.Id_membre = Membre.Id", con);
        adp.SelectCommand = command;

        adp.Fill(tabRetard);

        return View(tabRetard);
    }
}

现在我正尝试像这样向查询添加一个参数,但它抛出异常

System.Data.SqlClient.SqlException : 'Incorrect syntax near 'Retard'

我不知道是什么问题!

public ActionResult Details(int id)
{
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection con = new SqlConnection(chaineConnexion))
    {
        DataTable tabRetard = new DataTable();

        con.Open();

        SqlDataAdapter adp = new SqlDataAdapter();

        SqlCommand command = new SqlCommand(
            "SELECT Livre.titre, Membre.nom, " +
                "FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
                "LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
                "LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" +
                "WHERE Retard.Id_membre = @Id_membre", con);

        command.Parameters.AddWithValue("@Id_membre", id);

        adp.SelectCommand = command;
        adp.Fill(tabRetard);

        return View(tabRetard);
    }
}

这是由于您的字符串连接有错,Membre.IdWHERE 之间缺少空格:

SqlCommand command = new SqlCommand(
    "SELECT Livre.titre, Membre.nom, " +
        "FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
        "LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
        "LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" + /*Needs a space at the end*/
/*or at the beginning*/ "WHERE Retard.Id_membre = @Id_membre", con);

试试这个:

SqlCommand command = new SqlCommand(
    "SELECT Livre.titre, Membre.nom, " +
        "FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
        "LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
        "LEFT JOIN Membre ON Retard.Id_membre = Membre.Id " +
        "WHERE Retard.Id_membre = @Id_membre", con);

此外,尽量避免使用AddWithValue,因为它经常会导致查询参数出现问题,例如类型转换不正确、查询计划缓存膨胀等:

command.Parameters.AddWithValue("@Id_membre", id);

更喜欢使用 SqlCommandParameters.Add 方法,其中包含 SqlDbType 和长度参数,例如对于 int 个值:

command.Parameters.Add("@Id_membre", SqlDbType.Int).Value = id;

对于 string 值匹配相关 table/view 列的长度,例如:

command.Parameters.Add("@nom", SqlDbType.NVarChar, 50).Value = nom;

关于 AddWithValue 的有趣阅读: