Easier way to send parameterised query to database?

核能气质少年 提交于 2020-01-06 19:39:10

问题


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:


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)



来源:https://stackoverflow.com/questions/12930170/easier-way-to-send-parameterised-query-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!