2012-10-17 76 views
0

有没有办法在较少的行写下面的代码?这似乎有很多代码来执行这样一个简单的查询。没有LINQ,因为我正在使用VS2005。在VB或C#中的答案是可以接受的。更简单的方法将参数化查询发送到数据库?

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

回答

2

这些可能是线路最少可以得到:

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但类似其他数据提供商)

+0

我没有得到'AddWithValue'作为'可用的方法DbCommand.Parameters'。只有“添加”。 – CJ7

+0

然后你不使用'SqlClient',因为它是'SqlParameterCollection'的一个方法。你在使用什么数据提供者?即使在.NET 2中也可以在'OledbParameterCollection'中使用:http://msdn.microsoft.com/zh-CN/library/system.data.oledb.oledbparametercollection.addwithvalue(v=vs.80).aspx –

+0

The代码正在尝试迎合'OleDBConnection'或'SQLConnection',因此使用'DbCommand'。 – CJ7