搜索数据库表的值并将其放在数据表中

时间:2010-01-26 19:12:13

标签: c# asp.net sql search

我有一个文本框和一个搜索按钮,我试图在数据库表中搜索文件名并将其显示在数据表中...

private void GetSearchResults(string machineID, string searchFileName)
{
    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like '%@searchFileName%' AND MachineID=@machineID", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlCmd.Parameters.AddWithValue("@machineID", machineID);

    sqlCmd.Parameters.AddWithValue("@searchFileName", searchFileName);

    sqlDa.Fill(dt);
}

一切正常,但searchFileName在查询中不起作用...

我尝试只设置一个值来检查

SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like '%b%' AND MachineID=@machineID

我得到了文件值......

任何建议.. ??

3 个答案:

答案 0 :(得分:3)

您的变量位于字符串中,告诉数据库搜索文字字符串'@searchFileName'。要使用变量的值,请尝试此

'%' + @searchFileName + '%'

答案 1 :(得分:1)

以下是您的需求:

private void GetSearchResults(string machineID, string searchFileName)
{
    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like @searchFileName AND MachineID=@machineID", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlCmd.Parameters.AddWithValue("@machineID", machineID);

    sqlCmd.Parameters.AddWithValue("@searchFileName", String.Format("%{0}%",searchFileName);

    sqlDa.Fill(dt);
}

我之前遇到过这种情况。出于某种原因,它不知道如何在引号中解析参数。我想它认为这是一个文字。

答案 2 :(得分:1)

在您的选择中试试这个

SELECT FileID, BuFileName FROM BackedUpFiles where REGEXP_LIKE(upper(BuFileName ),UPPER(@searchFileName)) AND MachineID=@machineID;