2011-12-05 44 views
0

我做了這個程序,以幫助我重新使用選擇查詢:如果參數的數據類型是一個Object,我該如何將我查詢的值賦給一個String,它是一個過程中的參數?

Private Sub selectQry(ByVal myColumn As String, ByVal myTable As String, ByVal myFilter As String, ByVal myObjectOne As Object, ByVal myObj As Object) 
    Dim qrySlctCaldate As String = "SELECT " + myColumn + " FROM " + myTable + " WHERE " + myFilter + " = '" & Replace(myObjectOne, "'", "''") & "'" 
    Dim cmdSlct As New SqlCommand(qrySlctCaldate, transConn.Connection) 


    Dim readSCalDate As SqlDataReader 
    readSCalDate = cmdSlct.ExecuteReader 

    While readSCalDate.Read 
     If TypeOf (myObj) Is TextBox Or TypeOf (myObj) Is ComboBox Then 
      myObj.Text = readSCalDate.Item(myColumn).ToString 
     Else 
      myObj = readSCalDate.Item(myColumn).ToString 

     End If 
    End While 
    readSCalDate.Close() 

我這樣使用它,如果我想放置在文本框中選擇的值,它工作正常

selectQry("ProcConvDescription", "Line", "LineCode", nameValue.Value, txtProcess) 

但是,如果我想在一個字符串傳遞的價值,像這樣:

selectQry("LastCalibrationDate", "EquipmentItem", "ControlNo", txtControlNo.Text, strCalDate) 

字符串結束有一個空字符串值。如何將我查詢的值分配給該字符串?

回答

2

你應該修改你的方法是一個返回字符串的函數,而不是試圖在函數內部分配它。

Private Function selectQry(ByVal myColumn As String, ByVal myTable As String, 
          ByVal myFilter As String, ByVal myObjectOne As Object 
         ) As String 
    Dim qrySlctCaldate As String = _ 
     String.Format("SELECT {0} FROM {1} WHERE {2} = '{3}'", 
         myColumn, myTable, myFilter, 
         Replace(myObjectOne, "'", "''")) 
    Dim cmdSlct As New SqlCommand(qrySlctCaldate, transConn.Connection) 

    Using readSCalDate As SqlDataReader = cmdSlct.ExecuteReader 
     While readSCalDate.Read 
      Return readSCalDate.Item(myColumn).ToString 
     End While 
    End Using 
End Sub 

txtProcess.Text = selectQry("ProcConvDescription", "Line", "LineCode", nameValue.Value) 
strCalDate = selectQry("LastCalibrationDate", "EquipmentItem", "ControlNo", txtControlNo.Text) 

此外,我強烈建議打開Option Strict以獲得更好的類型安全性。

+0

爲什麼我不認爲這是超出我的。謝謝!但是,我怎麼不能將值分配給字符串的obj – Kurusu

+0

@Kurusu您正在執行的任務僅適用於本地變量。爲了影響調用方法的變量,您需要按照Bryce的建議傳遞ByRef。 –

1

嘗試通過MyObj中引用:

ByRef myObj As Object) 

...,看看有沒有什麼幫助。儘管我確實看到了能夠動態構建此查詢的價值,但您應該真正調整WHERE子句以使用sql參數(而不是SQL注入)。

" WHERE " + myFilter + " = @objectOne " 
cmdSlct.Parameters.Clear() 
cmdSlct.Parameters.AddWithValue("objectOne",myObjectOne) 
相關問題