vb.net 显示本周数据库记录

问题描述 投票:0回答:1

我在互联网上找到了一些其他参考资料,并尝试了到目前为止的代码,但似乎不起作用。有人可以帮助重新排列或修改我的代码以显示本周的记录吗?

Sub loadCheck()
    da = New MySqlDataAdapter("SELECT * FROM tblchecklist where check_corporate='" & mainfrm.lbl_server.Text & "' and select yearweek('2024-01-01 00:00:00'), yearweek(curdate())", conn)
    ds = New DataSet
    ds.Clear()
    da.Fill(ds, "tblchecklist")
    Me.DataGridView1.DataSource = (ds.Tables("tblchecklist"))
End Sub

我收到此错误:

异常用户未处理的 MySql.Data.MySqlClient.MySqlException: '您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“selectyearweek('2024-01-01 00:00:00'),yearweek(curdate())”附近使用的正确语法

sql mysql .net vb.net mariadb
1个回答
0
投票

问题出在这一段sql:

and select yearweek('2024-01-01 00:00:00'), yearweek(curdate())

不幸的是,问题中没有足够的信息来为您解决此问题,因为这似乎应该针对表中的特定列,而我们没有给出任何这些列的名称。

但为了提供答案,我假设我们应该使用一个名为

check_date
的列。在这种情况下,仍然存在一些含糊之处,但似乎您正在尝试这样做:

and yearweek(check_date) between yearweek('2024-01-01') and yearweek(curdate())

或者这个:

and yearweek(check_date) = yearweek(curdate())

请注意,这两者都不是最佳的。如果您计算所需范围的开始日期和结束日期,并使用半开放范围将这些日期提供为查询参数,并以范围结束后的一天为目标,则 SQL 将会更高效。

and check_date >= @StartDate and check_date < @EndDate
这将执行得更好,因为原始版本必须计算

表中的每一行的年周,而这不会对任何行进行操作,并且因为此选项仍然适用于原始版本不会使用索引的索引全部。

您还需要使用参数化查询。由于 ADO.Net 连接池,您也不应该尝试在任何地方重复使用相同的连接对象。为大多数查询分配一个新连接确实更好。您可以通过将

ALL 您的数据库代码移动到公共模块来简化此操作。

像这样把它们放在一起:

Public Module DB Private connectionString As String = " your connection string here " Public Function LoadCheck(Server As String) As DataTable ' Assuming you wanted the current week Dim StartDate As DateTime = DateTime.Today.AddDays(-Weekday(DateTime.Today, FirstDayOfWeek.System) + 1) Dim EndDate As DateTime = StartDate.AddDays(7) Dim result As New DataTable() Dim SQL As String = " SELECT * FROM tblchecklist WHERE check_corporate= @Server and check_date >= @StartDate and check_date < @EndDate" Using con As New MySqlConnection(connectionString), _ cmd As New MySqlCommand(SQL, con) da As New MySqlDataAdapater(cmd) cmd.Parameters.AddWithValue("@Server", Server) cmd.Parameters.AddWithValue("@StartDate", StartDate) cmd.Parameterse.AddWithValue("@EndDate", EndDate) da.Fill(result) End Using Return result End Function End Module ' ... Sub loadCheck() Me.DataGridView1.DataSource = DB.LoadCheck(mainfrm.lbl_server.Text) End Sub
    
© www.soinside.com 2019 - 2024. All rights reserved.