简体   繁体   中英

How to use variable dates in an SQL query inside vb.net without syntax 11 error

I have a basic vb.net program that pulls a query from an SQL database. My program works correctly if I hard code the date, however when I change the code from:

Dim dtstartdate As String = DateTime.Today
Dim dttomorrow As DateTime = DateTime.Today.AddDays(1)
Dim dtenddate As DateTime = dttomorrow.AddSeconds(-1)
Try
    For icounter = 1 To 2
        Call GetLocationInfo()



        connectionString = "Data Source=" & LocationDB & ";Initial Catalog=database;Persist Security Info=True;User ID=login;Password=password"


        sql = "select count(sTicket_number) as tickets from tickets where dtcreated between 2/8/2014 AND 2/9/2014 "
        sqlCnn = New SqlConnection(connectionString)

        sqlCnn.Open()

TO:

Dim dtstartdate As String = DateTime.Today
Dim dttomorrow As DateTime = DateTime.Today.AddDays(1)
Dim dtenddate As DateTime = dttomorrow.AddSeconds(-1)

Try
    For icounter = 1 To 2
        Call GetLocationInfo()



        connectionString = "Data Source=" & LocationDB & ";Initial Catalog=database;Persist Security Info=True;User ID=login;Password=password"


        sql = "select count(sTicket_number) as tickets from tickets where dtcreated between " & dtstartdate & " AND " & dtenddate & ""
        sqlCnn = New SqlConnection(connectionString)

        sqlCnn.Open()

I get a "Syntax Error near '11'" What am I doing incorrectly with the dtstartdate and dtenddate?

You need to be using SQL parameters instead. Otherwise you are looking for a lot of debugging in the long run + your code is vulnerable to SQL injection.

sql = "select count(sTicket_number) as tickets from tickets where dtcreated between @START_DATE AND @END_DATE"

Dim cmd As New SqlCommand(sql, sqlCnn)

cmd.Parameters.AddWithValue("@START_DATE", dtstartdate)
cmd.Parameters.AddWithValue("@END_DATE", dtenddate )

You need to enclose the dates in single quotes ( ' ). Additionally, I'd recommend getting into the practice of using parameterized queries to prevent SQL Injection Attacks. Something like this:

Using sqlCnn As SqlConnection = New SqlConnection(connectionString)

    sql = "select count(sTicket_number) as tickets from tickets where dtcreated between @StartDate AND @EndDate"
    SqlCommand cmd = new SqlCommand(sql);
    cmd.Parameters.AddWithValue("@StartDate", dtstartdate)
    cmd.Parameters.AddWithValue("@EndDate", dtenddate)

    sqlCnn.Open()

    ' Do the rest of your data access here

End Using

Using a parameterized query will both prevent SQL Injection Attacks and enable you to supply the parameter values without worrying about whether they need to be quoted or not.

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