在VB.Net中搜索过滤Mysql / Gridview

时间:2015-02-27 13:03:18

标签: mysql asp.net vb.net datepicker

我有2个文本框" TextBox1"和" TextBox2"和一个名为" Button1"的提交按钮 下面我有一个Label" Label1"

我需要做的是在"输入1&输入2" (YYYY-MM-DD) 并显示一个值(它只是计算表格中的记录)

这是我当前的查询

Dim c As New MySqlConnection("Server=localhost;Database=test;UID=test;PWD=test;")
c.Open()
Dim com As New MySqlCommand("SELECT COUNT(*) as c FROM toutcome WHERE AffID = '0001' AND CompletedDate >= CURDATE();", c)
Dim myReader As MySqlDataReader = com.ExecuteReader(CommandBehavior.CloseConnection)
myReader.Read()
Label1.Text = myReader.Item(0).ToString()

myReader.Close()

这是我试图用来完成上述任务的查询,它根本不起作用。

Dim c As New MySqlConnection("Server=localhost;Database=mdxmain;UID=MerryWoodTest;PWD=H0r$hamTest;")
c.Open()
Dim com As New MySqlCommand("SELECT COUNT(*) as c FROM toutcome WHERE AffID = '0001' AND WHERE CompletedDate >= '" & TextBox1.Text & "' AND CompletedDate <= '" & TextBox2.Text & "'", c)
Dim myReader As MySqlDataReader = com.ExecuteReader(CommandBehavior.CloseConnection)
myReader.Read()
Label11.Text = myReader.Item(0).ToString()

myReader.Close()

顶部查询有效,我得到一个值。

底部查询错误是

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近&#39; WHERE CompletedDate&gt; =&#39;&#39; AND CompletedDate&lt; =&#39;&#39;&#39;在第1行]

2 个答案:

答案 0 :(得分:0)

该行中的WHERE太多

... FROM toutcome WHERE AffID = '0001' AND WHERE ....
                                           ^^^^^

当然,更好的方法是使用参数化查询使命令文本更具可读性并防止Sql注入并在使用一次性对象时添加Using语句以在完成使用它们时释放它们的资源

Dim commandText= "SELECT COUNT(*) as c FROM toutcome " & _
                 "WHERE AffID = '0001' AND CompletedDate >= @init " & _
                 " AND CompletedDate <= @ending"
Using c = New MySqlConnection(".........")
Using com = new MySqlCommand(commandText, c)
    c.Open()
    com.Parameters.Add("@init", MySqlDbType.Date).Value = Convert.ToDateTime(TextBox1.Text)
    com.Parameters.Add("@ending", MySqlDbType.Date).Value = Convert.ToDateTime(TextBox2.Text)
    Using myReader = com.ExecuteReader(CommandBehavior.CloseConnection)
       if myReader.Read() Then
           Label11.Text = myReader.Item(0).ToString()
       End If
    End Using
End Using
End Using

答案 1 :(得分:0)

我还修复了我之前的错误查询,它正在运行。

   Dim x1 As New MySqlConnection("Server=test;Database=mdxmain;UID=test;PWD=testt;")
            x1.Open()
            Dim comx1 As New MySqlCommand("SELECT COUNT(*) as c FROM toutcome WHERE AffID = '" & CType(Session.Item("affID"), String) & "' AND CompletedDate >= '" & TextBox1.Text & "' AND CompletedDate <= '" & TextBox22.Text & "' AND Status = 'A'", x1)
            Dim myReaderx1 As MySqlDataReader = comx1.ExecuteReader(CommandBehavior.CloseConnection)
            myReaderx1.Read()
            Label12.Text = myReaderx1.Item(0).ToString()

            myReaderx1.Close()