2011-07-14 56 views
1

我該如何重寫它以便它使用參數而不是字符串值?我知道如何做一個「SqlCommand」,但我似乎無法在這裏工作。使用SQL參數重寫

protected void searchFill() 
    { 
     orderByString = orderByList.SelectedItem.Value; 
     fieldString = searchTextBox.Text; 
     string sqlStatement = "SELECT * FROM SecureOrders WHERE fName LIKE @fieldString OR lName LIKE @fieldString OR addr LIKE @fieldString OR addr2 LIKE @fieldString OR city LIKE @fieldString OR state LIKE @fieldString OR zip LIKE @fieldString OR zip LIKE @fieldString OR country LIKE @fieldString OR email LIKE @fieldString OR phone LIKE @fieldString OR ccType LIKE @fieldString OR ccNum LIKE @fieldString OR ccExp LIKE @fieldString OR cwaSource LIKE @fieldString OR cwaJoined LIKE @fieldString OR length LIKE @fieldString OR delivery LIKE @fieldString OR price LIKE @fieldString OR url LIKE @fieldString ORDER BY @orderByString"; 
     using (SqlConnection connection = new SqlConnection(connectionString.ToString())) 
     { 
      connection.Open(); 
      SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement, connection); 
      dataAdapter.SelectCommand.Parameters.AddWithValue("@fieldString", fieldString); 
      dataAdapter.SelectCommand.Parameters.AddWithValue("@orderByString", orderByString); 
      SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); 
      DataSet dataSet = new DataSet(); 

      dataAdapter.Fill(dataSet, "SecureOrders"); 

      DataView source = new DataView(dataSet.Tables[0]); 
      DefaultGrid.DataSource = source; 
      DefaultGrid.DataBind(); 
      connection.Close(); 
     } 
    } 

這裏是我的另一種方法,我現在用的參數(只是告訴你我知道如何略有使用它們)的SqlDataAdapter

protected void updateCheck(bool checkValue, int identity) 
    { 
     string checkStatement = "UPDATE dbo.SecureOrders SET processed = @Processed WHERE IdentityColumn LIKE @identity"; 
     using (SqlConnection connection = new SqlConnection(connectionString.ToString())) 
     using (SqlCommand _check = new SqlCommand(checkStatement, connection)) 
     { 
      _check.Parameters.Add("@Processed", SqlDbType.Bit).Value = checkValue; 
      _check.Parameters.Add("@identity", SqlDbType.Int).Value = identity; 
      connection.Open(); 
      _check.ExecuteNonQuery(); 
      connection.Close(); 
     } 
    } 
+0

我認爲這是vb.net?您應該將您正在使用的語言添加到問題的標籤中。 –

+3

@Marc B:看起來更像C# –

+0

@尼爾,它可能是非常錯誤的VB:D – musefan

回答

2

實例有一個屬性叫做SelectCommand可以附加參數爲:

var dataAdapter = new SqlDataAdapter(someQuery, someConnection); 
dataAdapter.SelectCommand.Parameters.AddWithValue("@someParam", someVar); 
+0

我已經更新了我的第一個代碼...現在我收到一個錯誤,說「由ORDER BY編號1標識的SELECT項包含一個變量作爲表達式的一部分,列位置。只有在引用列名稱的表達式進行排序時才允許使用變量「....任何想法? –

+0

我不相信'ORDER BY'子句可以接受一個變量。你可能想開始另一個具體的問題 - 但首先檢查重複。有人可能已經問過這個問題。 – Yuck