我如何使 sql select 动态字符串比较工作?

How do i make a sql select dynamic string comparison to work?

我正在尝试从 wpf 数据网格单击单元格中获取正确的字符串,我将在 sql select 语句中将其用于第二个 wpf 数据网格。 当输入静态字符串值时它会起作用,但不是来自动态字符串。我的代码有什么问题?

    private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
        string barcode_string = row["BarCode"].ToString();

        //string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
        string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = 'L002BO4'";
    }

当在 sql 语句中输入字符串时,它就像一个魅力,但当然我希望从大型数据库返回的动态字符串也能正常工作。

你可以试试下面的方法吗

 string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = "+ barcode_string;

您刚刚错过了一个 " 在您的查询的最后。试试这个

    string barcode_detail = "SELECT BarCode, PCBGUID 
       FROM TB_AOIResult WHERE
          BarCode = "+"\'" +barcode_string + "\'";

请不要在 SQL 语句中连接字符串。使用参数。检查您的数据库中条形码列的数据类型是否正确。

    private void DataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        DataTable dt = new DataTable();
        DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
        string barcode_string = row["BarCode"].ToString();

        //string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
        string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = @BarCode;";
        using (SqlConnection cn = new SqlConnection("Your connection string")) 
        {
            SqlCommand cmd = new SqlCommand(barcode_detail, cn);
            cmd.Parameters.Add("@BarCode", System.Data.SqlDbType.VarChar).Value = barcode_string;
            cn.Open();
            dt.Load(cmd.ExecuteReader());
            //use the data in the data table
        }
    }

编辑 测试字符串。添加 using System.Diagnostics 以使用 Debug.Print

        String literal = "L002BO4";
        String variable = row["BarCode"].ToString();
        if (literal.Length == variable.Length)
            Debug.Print("The length of the strings match");
        else
            Debug.Print("The lengths do not match");
        Char[] variableArray = variable.ToCharArray();
        Char[] literalArray = literal.ToCharArray();
        for (int index =0; index<literalArray.Length; index++)
        {
            if (variableArray[index] == literalArray[index])
                Debug.Print($"index {index} matches");
            else
                Debug.Print($"index {index} does not match");
        }