2011-01-11 93 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传递给查询对象。然后将标量结果保存到变量(结果)中。那么你可以做,如果结果是<>“”,做这样和那样的。