C# 向数据库发送参数化查询的更简单方法?
有没有办法用更少的行编写以下代码?执行这样一个简单的查询似乎需要很多代码。没有LINQ,因为我正在使用VS2005。VB或C#中的答案均可接受C# 向数据库发送参数化查询的更简单方法?,c#,.net,vb.net,visual-studio-2005,dbcommand,C#,.net,Vb.net,Visual Studio 2005,Dbcommand,有没有办法用更少的行编写以下代码?执行这样一个简单的查询似乎需要很多代码。没有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
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()
这些可能是您可以获得的最少线路:
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
但对于其他数据提供程序类似)我没有将AddWithValue
作为DbCommand.Parameters
的可用方法。只有Add
。那么您就不会像假设的那样使用SqlClient
,因为它是SqlParameterCollection
的一种方法。您使用的是什么数据提供商?甚至在.NET 2中,OledbParameterCollection
中也可以使用它:该代码试图满足OleDBConnection
或SQLConnection
的潜在需求,因此使用了DbCommand
。