访问数据库c#查询问题

时间:2012-08-29 10:29:27

标签: c# database ms-access

以下是我的问题的背景:我有一个组合框,当用户开始输入时,它应该从数据库表中的列中检索建议的项目。用户开始输入名称,程序应通过查看名字和姓氏来建议名称(数据库有两个单独的表)

以下是我的代码:

        try{
            String temp = nameCBox.Text;
            AutoCompleteStringCollection namesSuggestion = new AutoCompleteStringCollection();
            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:\\LogEntry\\LogEntry.accdb; Persist Security Info = False;");
            OleDbDataReader reader;
            conn.Open();
            String text2send = "Select Name from [Teachers] where FName like '" + temp + "' OR LName like '" + temp + "' Group by [Name]";
            OleDbCommand cmd = new OleDbCommand(text2send, conn);
            reader = cmd.ExecuteReader();
            if (reader.HasRows == true)
            {
                while (reader.Read())
                    namesSuggestion.Add(reader["temp"].ToString());
            }
            reader.Close();
            nameCBox.AutoCompleteCustomSource = namesSuggestion;

            conn.Close();
            }

错误: 1)我在组合框中看不到任何建议 2)当我输入组合框时,它会突出显示文本,当我再次键入其他内容时,它将写入上一个键入的字符。

请帮助 desktopmaker

2 个答案:

答案 0 :(得分:0)

由于您使用的是Like运算符,请尝试在两者之间进行输入:%input% 得到类似的东西:

看看this,它可能会有所帮助

var sql = String.Format("Select Name from [Teachers] WHERE FName Like '%{0}%' OR LName Like '%{0}%'", temp);

其他要点可能对您当前的代码有所帮助:

  • 在代码中使用using语句,它会处理资源,对于Connection,它会关闭它。

    using(var conn = new OleDbConnection("ConnectionStrong"))
    {
        //code
    }
    
  • 最好的方法是使用参数化查询Link

答案 1 :(得分:0)

这是做什么的

namesSuggestion.Add(reader["temp"].ToString()); 

读者正在返回一个名为Name ..的列。

我希望用户输入它时期望搜索字符串包含一个外卡。

E.g。标准sql中的Like 'John%'Like '%Smith',访问使用*代替%我似乎记得。

哦,大概你不担心sql注入攻击吗?

相关问题