我有下面的代码可以工作,但我需要为它添加更多功能。我想添加的功能是我在下面的代码中评论过的文本。
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 :(得分:1)
我不打算为你做所有这些,但是检查计数的简单方法是将存储过程(SQL Server)的结果存储到SqlDataReader中并检查计数是否> 0或如果HasRows = True。
With (myObjectCommand)
.Parameters.Add("@strUser", SqlDbType.Varchar, 3).Value = myUser
myReader = .ExecuteReader
End With
if myReader.HasRows
return true ?
end if
答案 1 :(得分:1)
足够简单。只需对数据库执行ExecuteScalar,例如“从表中选择字段1,其中username = @username”,并将strUser传递给查询对象。然后将标量结果保存到变量(结果)中。如果结果是<>那么你可以这样做“”,做这样的等等。