从C#代码,我试图执行一个查询并将两个参数传递给Access数据库。不幸的是,参数名称是相同的,因为我传递的是日期参数。似乎当我对代码进行了优化时,第一个参数被第二个参数替换,所以例如我正在传递
开始日期为1/1/2017,结束日期为1/31/2017
我仍然获得2016年的价值。
以下是我的代码
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= ? and compl_date <= ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("compl_date", StartDate); // startDate can be 1/1/2017
cmd.Parameters.AddWithValue("compl_date", EndDate); // end date could be 1/31/2017
conn.Open();
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
try
{
string FullLine = "";
如何获取上述日期范围内的值。
答案 0 :(得分:3)
尝试这样;
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= @StartDate and compl_date <= @EndDate";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@StartDate", StartDate);
cmd.Parameters.AddWithValue("@EndDate", EndDate);
conn.Open();
....