如何在两个日期之间进行搜索?

时间:2018-01-29 05:52:46

标签: c# mysql

我的代码无法正常工作时,我真的很开心。有人可以帮我解决如何使用datetimepicker在两个日期之间进行搜索的问题吗?我有一个源代码,可以从数据库中检索数据,但是当我在"之间添加"在where子句中,我想要搜索的数据,它不会在datagridview中显示。此外,我已经尝试过放置" MM / dd / yyyy"在tostring()。

检索数据的代码:

    public void showData()
    {
        string constring = "datasource = localhost;port = 3307; username = root; password =root; database = dbpetsales";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID',  ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos", conDataBase);
        try
        {

            MySqlDataAdapter sda = new MySqlDataAdapter();
            sda.SelectCommand = cmdDataBase;
            dbdataset = new DataTable();
            sda.Fill(dbdataset);
            BindingSource bSource = new BindingSource();

            bSource.DataSource = dbdataset;
            dataGridView1.DataSource = bSource;
            sda.Update(dbdataset);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

在两个日期之间搜索时检索数据的代码:

    public void showData()
    {
        string constring = "datasource = localhost;port = 3307; username = root; password =root; database = dbpetsales";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID',  ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos where Date between '"+this.dateTimePicker1.Value.ToString()+"' and '"+this.dateTimePicker2.Value.ToString()+"' ", conDataBase);
        try
        {

            MySqlDataAdapter sda = new MySqlDataAdapter();
            sda.SelectCommand = cmdDataBase;
            dbdataset = new DataTable();
            sda.Fill(dbdataset);
            BindingSource bSource = new BindingSource();

            bSource.DataSource = dbdataset;
            dataGridView1.DataSource = bSource;
            sda.Update(dbdataset);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:4)

首先,请在查询中使用参数而不是字符串concat(以防止sql注入并将日期作为日期发送,没有字符串),如下所示:

MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT transaction_ID as 'Transaction ID',  ProdName as 'Product Name',price as 'Price',subtotal as 'Subtotal', Date FROM dbpetsales.pos where Date >= @date1 and Date <= @date2, conDataBase);
cmdDataBase.Parameters.AddWithValue("@date1", dateTimePicker1.Value);
cmdDataBase.Parameters.AddWithValue("@date1", dateTimePicker2.Value);