参数与常规字符串相同

时间:2017-06-10 13:26:28

标签: c# sql-server wpf

当我在TextBox中键入'时,会导致错误。我知道因为'是SQL Query的一部分。我该如何避免?我已经使用参数完成了它,但是甚至没有工作。

    private void theFilter(string FilterValue) {
        string thisQuery = "SELECT * FROM [Customer] WHERE CONCAT([Name], [Address], [Discount]) LIKE '%" + @FilterValue + "%'";
        using(SqlConnection thisSqlConnection = new SqlConnection(theConnectionString))
        using(SqlCommand thisSqlCommand = new SqlCommand(thisQuery, thisSqlConnection)) {
            thisSqlCommand.Parameters.AddWithValue("@FilterValue", FilterValue);
            using(SqlDataAdapter thisSqlDataAdapter = new SqlDataAdapter(thisSqlCommand))
            using(DataTable thisDataTable = new DataTable()) {
                thisSqlDataAdapter.Fill(thisDataTable);
                DataGrid_Customer.ItemsSource = thisDataTable.DefaultView;
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

尝试使用此

private void theFilter(string FilterValue) {
    string thisQuery = "SELECT * FROM [Customer] WHERE CONCAT([Name], [Address], [Discount]) LIKE @FilterValue";
    using(SqlConnection thisSqlConnection = new SqlConnection(theConnectionString))
    using(SqlCommand thisSqlCommand = new SqlCommand(thisQuery, thisSqlConnection)) {
        thisSqlCommand.Parameters.AddWithValue("@FilterValue", "%" + FilterValue + "%");
        using(SqlDataAdapter thisSqlDataAdapter = new SqlDataAdapter(thisSqlCommand))
        using(DataTable thisDataTable = new DataTable()) {
            thisSqlDataAdapter.Fill(thisDataTable);
            DataGrid_Customer.ItemsSource = thisDataTable.DefaultView;
        }
    }
}

请记住,您在参数中使用字符串,而不是变量。您必须在AddWithValue方法中指明'%'才能在查询中使用通配符。

答案 1 :(得分:3)

extern long int f1(long int *arr_ptr[]);
void main()
{
  long int arr1[4]= {113891, 319762, 987431, 765437}; 
  long int arr2[4]= {567434, 988885, 654329, 999990}; 
  long int arr3[4]= {123456, 999999, 888880, 498766}; 
  long int *arr_ptr[3];
  arr_ptr[0] = arr1;
  arr_ptr[1] = arr2;
  arr_ptr[2] = arr3;
  f1(arr_ptr);}