【问题标题】:Filtering a Date (string) converted to date SQL Query in a MVC application在 MVC 应用程序中过滤转换为日期 SQL 查询的日期(字符串)
【发布时间】:2021-08-24 10:42:30
【问题描述】:

所以目前,我正在一家公司翻新一个应用程序,在该应用程序中,我被要求创建一个表单,我可以在其中提交一个日期,然后在另一个屏幕(剃须刀页面)上我向 bd 询问两者之间的信息日期。

所以这是应该“打印”表格的代码的一部分

public partial class Espolio : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvbindespolios();
                EspoliosSearch();
                //FilterPageLoader();
            }
        }

        


        //Method of the searchboxes for the menu Espolio
        protected void EspoliosSearch()
        {
            string constr = ConfigurationManager.ConnectionStrings["Carrier_LASOConnection"].ConnectionString;

            string querycentroc = "select distinct isnull(vd.costcentercode,'') [CC] from tms.vehicledetails vd inner join tms.vehicles v on v.licenceplate=vd.LicensePlateNumber where v.isdeleted=0 order by isnull(vd.costcentercode,'') ASC";

            using (SqlConnection con = new SqlConnection(constr))
            {
                // Lists the costcented cordes ( filters by cost center ) 
                using (SqlCommand cmdcentroc = new SqlCommand(querycentroc))
                {
                    SqlDataReader srcentroc;

                    cmdcentroc.Connection = con;
                    cmdcentroc.Connection.Open();

                    srcentroc = cmdcentroc.ExecuteReader();

                    while (srcentroc.Read())
                    {
                        System.Web.UI.WebControls.ListItem listcentroc = new System.Web.UI.WebControls.ListItem();

                        listcentroc.Value = srcentroc["cc"].ToString();
                        listcentroc.Value = srcentroc["cc"].ToString();

                        Ddepartamento.Items.Add(listcentroc);
                    }

                    Ddepartamento.Items.Insert(0, new ListItem("", ""));
                    srcentroc.Close();
                    cmdcentroc.Connection.Close();
                }
            } 
        }

        
        // Method which "fills" the table ( MAIN )
        protected void gvbindespolios()
        {
            string constr = ConfigurationManager.ConnectionStrings["Carrier_LASOConnection"].ConnectionString;
            string strName = HttpContext.Current.User.Identity.Name.ToString().Replace("LASODOM\\", "");

            String Nome = strName;

            string queryespolio = @"Select e.Id, e.Matricula[Matrícula], v.Brand[Marca], e.DataEspolio[Data do Espólio], d.name[Nome Motorista], e.IDMotorista[ID Motorista], vd.Mobile[Móvel], CostCenterCode[Centro de Custo]
                                    From Laso.Espolios e
                                inner Join Tms.Vehicles v on v.LicencePlate = e.Matricula
                                inner Join Tms.Drivers d on d.Id= e.IDMotorista
                                inner Join Tms.VehicleDetails vd on vd.LicensePlateNumber = v.LicencePlate
                                    where v.isdeleted=0 and
                                replace(vd.LicensePlateNumber,' ','') like '%" + TMatricula.Text.Replace(" ", "") +
                                "%' and replace(vd.mobile,' ','') like '%" + Tmovel.Text.Trim() +
                                "%' and e.DataEspolio like '%" + Tdatainicio.Text +
                                "%' and d.name like '%" + Tmotoristanome.Text.ToString() +
                                "%' and vd.costcentercode like '%" + Ddepartamento.SelectedValue.ToString().TrimEnd().TrimStart() +
                                "%' and v.Brand like '%" + Tmarca.Text.ToString().TrimEnd().TrimStart() +
                                "%' and d.Id like '%" + Tmotorista.Text.ToString() + "%'" +
                                " and (@datainicio != '' AND @datafim != '' AND dataespolio between TRY_CONVERT(date, @datainicio, 23) AND TRY_CONVERT(date, @datafim, 23)) OR " +
                                "(@datainicio != '' AND @datafim = '' AND dataespolio between TRY_CONVERT(date, @datainicio, 23) and getdate()) OR " +
                                "(@datainicio = '' AND @datafim = '')" + "order by e.Id Desc";

            SqlParameter pardatinc = new SqlParameter("@datainicio", Tdatainicio.Text);
            SqlParameter pardatfim = new SqlParameter("@datafim", Tdatafim.Text);

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmdespolio = new SqlCommand(queryespolio))
                {
                    cmdespolio.Parameters.Add(pardatinc);
                    cmdespolio.Parameters.Add(pardatfim);

                    using (SqlDataAdapter sdaespolio = new SqlDataAdapter())
                    {
                        cmdespolio.Connection = con;
                        cmdespolio.Connection.Open();
                        sdaespolio.SelectCommand = cmdespolio;
                        using (DataTable dtespolio = new DataTable())
                        {
                            sdaespolio.Fill(dtespolio);

                            GvEspolios.DataSource = dtespolio;
                            GvEspolios.DataBind();
                            ViewState["dirStateespolio"] = dtespolio;
                            ViewState["sortdrespolio"] = "Desc";
                        }
                    }
                }
            }
        }

        protected void Tpesquisar_Click(object sender, EventArgs e)
        {
            gvbindespolios();
        }

        protected void Tclear_Click(object sender, EventArgs e)
        {
            TMatricula.Text = "";
            Tmotorista.Text = "";
            Tmotoristanome.Text = "";
            Ddepartamento.ClearSelection();
            Tmovel.Text = "";
            Tmarca.Text = "";
            Tdatainicio.Text = "";
            Tdatafim.Text = "";
        } 

前端 所以这里是前端:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div style="height:950px; width:1500px; background:#ffffff;" class="auto-style8">

    <style type="text/css">
    </style>
        <div class="jumbotron">
        <asp:Panel ID="Panel3" runat="server" 
                   BackColor="#005172" ForeColor="White" 
                   Font-Size="Large" Font-Names="Helvetica">
                <label class="LabelTitulo">Espólios</label> 
            </asp:Panel>
         <br />
            <!-- Tabela com campos de search Espolios-->
            <table>
               <tr dir="auto">
                <td style="color: #a3a8b8; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: bold">
                    <label class="Label">Matrícula</label><br /><asp:TextBox ID="TMatricula" cssClass="TextBox" TextMode="Search" runat="server" style="text-transform:uppercase"></asp:TextBox>
                </td>
                   <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Marca</label><br /><asp:TextBox ID="Tmarca" runat="server" cssClass="TextBox" TextMode="Search"></asp:TextBox> 
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Móvel</label><br /><asp:TextBox ID="Tmovel" runat="server" cssClass="TextBox" TextMode="Search"></asp:TextBox> 
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Desde</label><br /><asp:TextBox ID="Tdatainicio" runat="server" cssClass="TextBox" TextMode="Date"></asp:TextBox> 
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Até</label><br /><asp:TextBox ID="Tdatafim" runat="server" cssClass="TextBox" TextMode="Date"></asp:TextBox> 
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Motorista</label><br /><asp:TextBox ID="Tmotoristanome" runat="server" cssClass="TextBox" TextMode="Search"></asp:TextBox> 
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                    <label class="Label">ID Motorista</label><br /><asp:TextBox ID="Tmotorista" ccsClass="Textbox" TextMode="Search" runat="server" ></asp:TextBox>
                </td>
                <td dir="auto" style="font-family: Arial, Helvetica, sans-serif; color: #a3a8b8; font-weight: bold; font-size: small;">
                     <label class="Label">Centro Custo</label><br /><asp:DropDownList ID="Ddepartamento" runat="server" cssClass="TextBox" TextMode="Search"></asp:DropDownList> 
                </td>
                 
               </tr>
            </table>
             <!-- FIM Tabela com campos de search Espolios-->
            <asp:Button ID="Tpesquisar"
                        runat="server"
                        cssClass="buttonwhite"
                        OnClick="Tpesquisar_Click"
                            Text="Pesquisar"
                            />
            <asp:Button ID="Tclear"
                        runat="server"
                        cssClass="buttonwhite"
                        text="Limpar filtro"
                        OnClick="Tclear_Click"   
                            />
                        <!--OnClick="Tclear_Click"-->

            <asp:Button ID="Tinserirespolio" 
                        runat="server"
                        cssClass="button"
                        OnClick="Tinserirespolio_Click"
                            Text="Novo Espólio"
                             />
            
            <asp:Button ID="Texportarespolio" 
                        runat="server"
                        cssClass="button"
                        OnClick="Texportarespolio_Click"
                            Text="Exportar Tabela"/>
           
            <asp:Button ID="Texportarhistoricoesp" 
                        runat="server"
                        cssClass="button"
                        OnClick="Texportarhistoricoesp_Click"
                            Text="Exportar Histórico"/>
         <asp:GridView ID="GvEspolios"
                       style="
                            margin-left:10px;
                            margin-top:18px;
                            width:99%" 
                       runat="server" DataKeyNames="id" CellPadding="15"
                       ForeColor="#7C839B" Font-Names="Helvetica" Font-Size="Smaller"
                       GridLines="Horizontal" BorderColor="#CCCCCC" BorderStyle="none"
                       BackColor="White" 
                       ShowHeaderWhenEmpty="True" CellSpacing="2"
                       OnPageIndexChanging="GvEspolios_PageIndexChanging"
                      >
                       
             <Columns>
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:ImageButton ID="ImageButton1" 
                                             runat="server" 
                                             CausesValidation="false" 
                                             CommandName="" 
                                             ImageUrl="~/content/Imagens/edit.png" 
                                             Text="Detalhes" 
                                             Height="25px" Width="25px" 
                                             OnClick="Detalhesespolios_Click"/>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle Font-Names="Oswald" />
                <HeaderStyle BackColor="White" 
                             Font-Bold="False"
                             Font-Names="Helvetica"
                             ForeColor="#A3A8B8"
                             Font-Size="12px"/>
                <AlternatingRowStyle BackColor="#F9F9F9" />
                <PagerStyle ForeColor="#7c839b" 
                            BackColor="White" 
                            Font-Names="Helvetica" 
                            Font-Size="Small" />
            </asp:GridView>
        </div>
    </div>
    </asp:Content>

例如,我在数据库上有一个日期为 2021-05-26 的寄存器 当我尝试搜索该日期之前的值时,它不应该出现。它没有,所以它是正确的。但是,当我选择包含该日期 (26) 的日期戳时,它也不会出现。

我可以做对,但我不明白为什么现在我不能过滤它。

如果我对数据库执行相同的查询,我实际上可以看到该值。

DECLARE @datainicio NVARCHAR(10)
DECLARE @datafim NVARCHAR(10)

SET @datainicio = '2021-05-20'
SET @datafim = '2021-05-27'

SELECT e.Id,
       e.Matricula   [Matrícula],
       v.Brand       [Marca],
       e.DataEspolio [Data do Espólio],
       d.NAME        [Nome Motorista],
       e.IDMotorista [ID Motorista],
       vd.Mobile     [Móvel],
       CostCenterCode[Centro de Custo]
FROM   laso.Espolios e
       INNER JOIN tms.Vehicles v
               ON v.LicencePlate = e.Matricula
       INNER JOIN tms.Drivers d
               ON d.Id = e.IDMotorista
       INNER JOIN tms.VehicleDetails vd
               ON vd.LicensePlateNumber = v.LicencePlate
WHERE  v.isdeleted = 0
       AND Replace(vd.LicensePlateNumber, ' ', '') LIKE '%%'
       AND Replace(vd.mobile, ' ', '') LIKE '%%'
       AND e.DataEspolio LIKE '%%'
       AND d.NAME LIKE '%%'
       AND vd.costcentercode LIKE '%%'
       AND v.Brand LIKE '%%'
       AND d.Id LIKE '%%'
       AND ( @datainicio != ''
             AND @datafim != ''
             AND dataespolio BETWEEN Try_convert(date, @datainicio, 23) AND
                                     Try_convert(date, @datafim, 23) )
        OR ( @datainicio != ''
             AND @datafim = ''
             AND dataespolio BETWEEN Try_convert(date, @datainicio, 23) AND
                                     Getdate() )
        OR ( @datainicio = ''
             AND @datafim = '' )
ORDER  BY e.Id DESC 

【问题讨论】:

  • 不要将日期转换为字符串。不要连接字符串来创建 SQL 查询,使用参数化查询。连接字符串会使您面临 SQL 注入攻击(想象一下将 '; drop table users ;-- 作为输入会发生什么情况`转换错误,就像您遇到的那样
  • 如果您使用参数化查询和像DateTime 这样的强类型值,您将能够消除所有这些转换尝试并简化代码很多。例如dataespolio between @datainicio and @datafim
  • 我发现还有其他 SQL 注入问题。 replace(vd.LicensePlateNumber,' ','') like '%" + TMatricula.Text.Replace(" ", "") 变成了 replace(vd.LicensePlateNumber,' ','') like '%%'。这将扫描。整个表,但什么都不过滤。此查询存在严重的安全和性能问题
  • 感谢 Panagiotis 的提示。我是一名实习生,所以目前我正在努力学习做事的最佳方式,我做出的大部分决定都来自我在互联网上找到的信息。我会改变那些其他问题。
  • come from what I find on the internet 这是一个非常的坏主意。您需要了解正在发生的事情才能判断您阅读的内容是好是坏。根据定义,其中一半将低于平均水平。如果您想了解如何使用 Razor Pages,请阅读 Microsoft tutorials 和知名课程(即不是 Udemy)。知名作者不会发表废话,否则他们会倒闭。 Google 搜索永远不会忘记错误

标签: c# sql asp.net-mvc


【解决方案1】:

SqlParameter 不需要更改日期格式,您可以设置DataType 来解决您的问题。

SqlParameter property

如果没有解决您的问题,您可以将 DateText 更改为 DateTime

var yourDate = Convert.ToDateTime(Tdatainicio.Text).ToString("yyyy-MM-dd");

希望能解决你的问题

【讨论】:

  • 嗨 Zanyar,我已经尝试了多种方法,但目前没有一个选项有效。当我将日期过滤器添加到查询中时,它只搜索日期,如果我使用任何其他值,它会一直加载相同的唯一值。但无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多