gpt4 book ai didi

C# 使用 sql LIKE 过滤 datagridview 日期时间字段

转载 作者:行者123 更新时间:2023-11-29 11:19:05 26 4
gpt4 key购买 nike

当我尝试从 datagridview 过滤数据时遇到问题。我尝试使用 LIKE% 通配符过滤 datetime 字段。当我像这样 12-01 那样在 textBoxEdit 中分配值或只是输入 1 时,得到:

enter image description here

我是否没有对该查询字符串进行格式化和转义,或者无法将整数值分配给通配符?或者可能是此语法错误的任何其他原因。

另一个查询工作正常,只是在这里我遇到问题:

sql = "SELECT * FROM grupe_artikala WHERE  CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";

检查我的完整代码:

 private void searchTextBoxNaziv_TextChanged(object sender, EventArgs e)
{
String selectedColumn = filterSearchCombo.Text;
String sql = "";

if(selectedColumn == "ID" && searchTextBoxNaziv.Text is string)
{
sql = "SELECT * FROM grupe_artikala WHERE id LIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if(selectedColumn == "Name")
{
sql = "SELECT * FROM grupe_artikala WHERE nameLIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if (selectedColumn == "Descr")
{
sql = "SELECT * FROM grupe_artikala WHERE desc LIKE '%" + searchTextBoxNaziv.Text + "%'";
}
else if (selectedColumn == "Created")
{
sql = "SELECT * FROM grupe_artikala WHERE CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'";

}

else
{
sql = "SELECT * FROM grupe_artikala";
}

GetData(sql);
}

更新:

private void GetData(string sql)
{
using (conn = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
try
{
conn.Open();

adapter = new MySqlDataAdapter(sql, conn);

dt = new DataTable();
bs = new BindingSource();

adapter.Fill(dt);

bs = new BindingSource();
bs.DataSource = dt;

dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}

最佳答案

您不需要将日期转换为 varchar

SELECT * FROM grupe_artikala WHERE  CONVERT(VARCHAR, created, 120) LIKE '" + searchTextBoxNaziv.Text + "%'

改为使用下面的查询

SELECT * FROM grupe_artikala WHERE  created LIKE '" + searchTextBoxNaziv.Text + "%'

它会简单地根据where条件搜索数据。

关于C# 使用 sql LIKE 过滤 datagridview 日期时间字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com