Easier way to send parameterised query to database?

210 views Asked by At

Is there a way to write the following code in less lines? It seems like a lot of code to execute such a simple query. No LINQ as I am using VS2005. Answers in either VB or C# are acceptable.

Using cmd As DbCommand = oDB.CreateCommand()
    cmd.CommandText = "SELECT * FROM [Table1] WHERE [Date] BETWEEN @Date1 AND @Date2"
    cmd.CommandTimeout = 30
    cmd.CommandType = CommandType.Text
    cmd.Connection = oDB
    Dim param As DbParameter
    param = cmd.CreateParameter()
    param.Direction = ParameterDirection.Input
    param.DbType = DbType.Date
    param.ParameterName = "@Date1"
    param.Value = Now().Date
    cmd.Parameters.Add(param)
    param = cmd.CreateParameter()
    param.Direction = ParameterDirection.Input
    param.DbType = DbType.Date
    param.ParameterName = "@Date2"
    param.Value = Now().Date.AddDays(intDaysAhead)
    cmd.Parameters.Add(param)
End Using
Dim reader As DbDataReader = cmd.ExecuteReader()
1

There are 1 answers

3
Tim Schmelter On

These are probably the fewest lines you can get:

Using con = New SqlConnection("Connectionstring")
    Using cmd = New SqlCommand("SELECT * FROM [Table1] WHERE [Date] BETWEEN @Date1 AND @Date2", con)
        cmd.CommandTimeout = 30
        cmd.Parameters.AddWithValue("@Date1", Date.Today)
        cmd.Parameters.AddWithValue("@Date2", Date.Today.AddDays(intDaysAhead))
        con.Open()
        Using reader = cmd.ExecuteReader()

        End Using
    End Using
End Using

(assuming SqlClient but similar for other data providers)