如何使用 MS Access 在 C# 中的两个日期之间进行搜索
本文关键字:两个 日期 之间 搜索 Access MS 何使用 | 更新日期: 2023-09-27 18:33:38
所以对于一个小组项目,我需要能够在两个日期"Start_Date"和"End_Date"之间搜索。这两个字段都使用数据库中名为"study_date"的列。目前,我只能通过在任一字段中输入指定的日期来搜索一个日期。
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
//The code for the button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text)? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text)? "%" : txtStart.Text;
//DateTime start = DateTime.Parse(Start_Date);
string End_Date = String.IsNullOrEmpty(txtEnd.Text)? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text)? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(txtComment.Text)? "%" : txtComment.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|''Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|''Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
}
}
你可以
试试这个
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date >=#" + Start_Date + "#" + "AND study_date <=#" + End_Date + "#" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
我想其他几个人在这里提到了它,但永远不要在SQL中为你的"where"子句做字符串连接。 它只是在招致各种各样的问题。
你想要的是参数,也就是绑定变量。 这些用作占位符 - 一种说"编译此SQL,我稍后会为您提供值"的方式。
参数具有许多优点:
- 它们阻止了SQL注入 - 无论多么罕见和难以实现,这始终是一种可能性;为什么要招致风险? 特别是当你的数据来自文本框时,你几乎是在乞求有人尝试。
- 它们使您的代码更加清晰。 所有这些加号,单引号,双引号让我头晕目眩
- 您通常可以保持SQL原始状态 - 将其复制并粘贴到SQL编辑器中,而不必修剪SQL串联中涉及的讨厌字符。 好的,所以对于Access来说并非如此,但是对于其他RDBMS,能够剪切和粘贴会产生很大的不同 。
- 它们解析数据类型 - 您不需要在 Access 的日期周围放置 #hash 标记#或对字符串(甚至不是引号(执行任何特殊操作 - 请参阅下面的示例
- 它们处理特殊字符。 例如,如果您的一个文本框包含
I think I'll go to the park
,则该撇号将转换为单个引号,这会破坏您的查询。 有了参数,你就不用担心了
下面是查询的参数化版本的示例:
string Select = @"
SELECT * FROM tblReject_test
WHERE
department_id ALIKE @Department & '%' AND
body_part_examined ALIKE @Anatomy & '%' AND
reject_category ALIKE @RFR & '%' AND
reject_comment ALIKE @Comment & '%' and
study_date >= @Start_Date and
study_date <= @End_Date
";
OleDbCommand cmd = new OleDbCommand(Select, DataConnection);
cmd.Parameters.AddWithValue("@Department", txtDepartment.Text);
cmd.Parameters.AddWithValue("@Anatomy", txtAnatomy.Text);
cmd.Parameters.AddWithValue("@RFR", cmbRFR.Text);
cmd.Parameters.AddWithValue("@Comment", txtComment.Text);
DateTime startDate, endDate;
if (!DateTime.TryParse(txtStart.Text, out startDate))
startDate = DateTime.MinValue;
if (!DateTime.TryParse(txtEnd.Text, out endDate))
endDate = DateTime.MaxValue;
cmd.Parameters.AddWithValue("@Start_Date", startDate);
cmd.Parameters.AddWithValue("@End_Date", endDate);
另一个离别镜头 - 使用文本框作为日期 - 如果您使用日期/时间控件,这将更加干净。 分析将起作用,但对于控件本机执行的操作来说,这是很多额外的工作。
cmd.Parameters.AddWithValue("@Start_Date", dateTimePickerStart.Value);
哦,顺便说一句,我想我回答了您关于此建议解决方案中开始日期和结束日期之间的日期的问题。