将参数化查询发送到数据库的更简单方法? [英] Easier way to send parameterised query to database?

查看:192
本文介绍了将参数化查询发送到数据库的更简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用更少的行写下面的代码?似乎有很多代码可以执行这种简单的查询.没有LINQ,因为我正在使用VS2005.可以使用VB或C#进行回答.

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()

推荐答案

这些可能是您可以获得的最少行:

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

(假设SqlClient,但与其他数据提供者相似)

(assuming SqlClient but similar for other data providers)

这篇关于将参数化查询发送到数据库的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆