C# 如何使用MS Access在C中搜索两个日期
所以对于一个团队项目,我需要能够在两个日期之间搜索开始日期和结束日期。这两个字段都使用数据库中一个名为study_date的列。目前,我只能通过在任一字段中输入指定日期来搜索一个日期 这是我的密码:C# 如何使用MS Access在C中搜索两个日期,c#,date,ms-access,between,C#,Date,Ms Access,Between,所以对于一个团队项目,我需要能够在两个日期之间搜索开始日期和结束日期。这两个字段都使用数据库中一个名为study_date的列。目前,我只能通过在任一字段中输入指定日期来搜索一个日期 这是我的密码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.
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,能够剪切和粘贴会有很大的不同 它们解析数据类型-您不需要在访问日期周围加上哈希标记,也不需要对字符串做任何特殊的操作,甚至不需要引号-请参见下面的示例 它们处理特殊字符。例如,如果您的一个文本框包含“我想我会去公园”,则该撇号将转换为单个引号,这将破坏您的查询。对于参数,您不必担心 以下是查询的参数化版本示例:
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);
哦,顺便说一句,我想我已经回答了您的问题,即在这个建议的解决方案中,日期介于开始日期和结束日期之间。我尝试了这个方法,每次搜索时都会出现一个错误,错误是:条件表达式中的数据类型不匹配。字符串连接是所有SQL注入错误的根源。使用参数化查询,以便注释';升降台tblReject_测试;-不会破坏你的数据库。或者像我尝试过但失败一样输入注释不会使应用程序崩溃如果您在DB表中存储date is date字段,则使用“而不是”。请参阅编辑的回答使用cdateStart_日期和CDATEND_日期,因为它们是字符串而不是日期。此外,作为故障保护,如果不是db中的日期,您也可以将研究日期转换为日期。。。。。。。cdatestudy_date=cdate+End_date+..大家好,谢谢你们的回复。不幸的是,上述选项都不起作用@DiscipleMichael,你能帮我把代码放到完整的选择字符串中吗?当我试图在它的当前状态下使用它时,它只是一团乱,根本不起作用。注意,Aaron请不要使用字符串连接来生成SQL语句。使用适当的参数化查询。任何数量的有效字符都可能导致错误,例如我尝试过但失败的注释将中断查询。您好,谢谢您提供的有用代码。虽然我不怀疑它是有效的,我无法确认它,因为当我使用它并尝试在我的程序中搜索记录时,我收到一条弹出消息说:一个或多个必需参数没有给定值,这通常意味着它是一个输入错误-就像我创建了一个名为@Department的参数,但实际上绑定了一个名为@Dept的参数。我检查了代码,乍一看,它出现了,一切都匹配。我可以模拟一个DB并测试它,看看我是否得到了同样的结果。嗯,我不确定。。。我对它进行了模拟,它完全按照预期工作。我能看到的唯一不同之处是,您使用的是.mdb文件,而我的是.accdb文件。出于好奇,你能切换到新的格式,看看它是否有效吗?您好,很抱歉延迟了回复。我尝试过使用.accdb格式,visual Studio一直告诉我这是一种无法识别的数据库格式,这就是为什么我首先选择使用.mdb。
cmd.Parameters.AddWithValue("@Start_Date", dateTimePickerStart.Value);