2011-01-11 92 views
1

我有下面的代碼工作,但我需要添加更多的功能。我想添加的功能是我在下面的代碼中評論過的文本。數據庫中的記錄計數

Dim objSQLConnection As SqlConnection 
Dim objSQLCommand As SqlCommand 

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) 
    Dim intID As Integer = CType(Request.Form("ID"), Integer) 
    Dim strHeading As String = CType(Request.Form("Heading"), String) 
    Dim intState As Integer = CType(Request.Form("State"), Integer) 
    Dim strUser As String = CType(Request.Form("User"), String) 

    objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString")) 

    ''#count if records with this user already exist in the database below 

    If intState = 1 Then 
     objSQLCommand = New SqlCommand("insert into table1 (id, heading, user) values (@intID, @strHeading, @strUser)", objSQLConnection) 

     objSQLCommand.Parameters.Add("@intID", SqlDbType.Int, 4).Value = intID 
     objSQLCommand.Parameters.Add("@strHeading", SqlDbType.VarChar, 255).Value = strHeading 
     objSQLCommand.Parameters.Add("@strUser", SqlDbType.VarChar, 3).Value = strUser 
    ElseIf intState = 0 Then 
     objSQLCommand = New SqlCommand("delete from table1 where id = @intID and user = @strUser", objSQLConnection) 

     objSQLCommand.Parameters.Add("@intID", SqlDbType.Int, 4).Value = intID 
     objSQLCommand.Parameters.Add("@strUser", SqlDbType.VarChar, 3).Value = strUser 
    End If 

    objSQLCommand.Connection.Open() 
    objSQLCommand.ExecuteNonQuery() 
    objSQLCommand.Connection.Close() 
End 

if語句之前,我想找出如果數據庫已經記錄在該strUser的變量名。做這件事的最好方法是什麼?

+0

請不要轉發相同的問題:http://stackoverflow.com/questions/4658869/duplicate-default-records-if-user-has-no-records – 2011-01-11 15:02:58

回答

1

我不打算爲你做所有這些,但檢查計數的一種簡單方法是將存儲過程(SQL Server)的結果存儲到SqlDataReader中,並檢查count> 0或HasRows =真正。

With (myObjectCommand) 
    .Parameters.Add("@strUser", SqlDbType.Varchar, 3).Value = myUser 
    myReader = .ExecuteReader 
End With 

if myReader.HasRows 
    return true ? 
end if 
1

夠簡單。只需在數據庫上執行ExecuteScalar,並使用「從where username = @username」的表中選擇field1,然後將strUser傳遞給查詢對象。然後將標量結果保存到變量(結果)中。那麼你可以做,如果結果是<>「」,做這樣和那樣的。