如何使用WHERE条件显示记录

时间:2018-05-15 00:20:19

标签: c# mysql

我正在使用C#和MySQL创建一个应用程序。 MySQL表(tbl_sales)有四个字段(sale_item, sale_qty, added_n and last_updated_on)。 last updated_on字段的数据类型为DateTime。我想根据以下SQL在DataGridView中显示记录。 SELECT * FROM tbl_sales WHERE last_updated_on >=" + dateTimePicker1.Text;

我收到以下错误You have and error in your SQL syntax; check the manual that corrosponds to yout MySQL server version for the right syntax to use near " at line 1

我使用了以下C#代码

private void button1_Click(object sender, EventArgs e)
    {
        string query;
        try
        {
            conLocal.Open();
            query = "SELECT * FROM tbl_sales WHERE last_updated_on >=" + textBox1.Text; // Convert.ToString(dateTimePicker1.Text);

            cmdLocal = new MySqlCommand();
            cmdLocal.Connection = conLocal;
            cmdLocal.CommandText = query;
            da = new MySqlDataAdapter();
            da.SelectCommand = cmdLocal;
            dt = new DataTable();
            da.Fill(dt);

            dataGridView1.DataSource = dt;

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

        finally
        {
            da.Dispose();
            conLocal.Close();
        }
}

MySQL table data Without WHERE condition With WHERE condition

2 个答案:

答案 0 :(得分:1)

正如 Chetan Ranpariya 所说,你可以设置一个带MySqlDbType.DateTime数据类型的参数,将日期值传递给查询,如下所示:

query = "SELECT * FROM tbl_sales WHERE last_updated_on >= @last_updated";

// conLocal is a MySqlConnection
using (var cmdLocal = new MySqlCommand(query, conLocal))
{
    cmdLocal.Parameters.Add("@last_updated", MySqlDbType.DateTime).Value = DateTime.Parse(dateTimePicker1.Text);

    // execute query & bind to DataGridView here
}

如果日期选择器中传递的字符串值具有预先指定的格式(例如yyyy-MM-dd HH:mm:ss),则在分配参数值时使用DateTime.ParseExact

cmdLocal.Parameters.Add("@last_updated", MySqlDbType.DateTime).Value = DateTime.ParseExact(dateTimePicker1.Text, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

答案 1 :(得分:0)

可能您应该在单引号内包含日期时间文本值。一些东西。解析语句会在无效日期上抛出异常,因此请相应地处理它。

var lastUpdatedValue = DateTime.Parse(textBox1.Text);
var query = $"SELECT * FROM tbl_sales WHERE last_updated_on >='{lastUpdatedValue}'"

最后但同样重要的是,推荐的方法是使用parameterized queries而不是字符串。