【问题标题】:Count records in database统计数据库中的记录
【发布时间】:2023-03-03 01:42:01
【问题描述】:

我有下面的代码,它确实有效,但我需要向它添加更多功能。我要添加的功能是我在下面的代码中注释的文本。

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 变量中包含用户名的记录。这样做的最佳方法是什么?

【问题讨论】:

标签: .net asp.net sql vb.net .net-3.5


【解决方案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

【讨论】:

    【解决方案2】:

    足够简单。只需使用“从用户名 = @username 的表中选择字段1”之类的查询对数据库执行 ExecuteScalar,然后将 strUser 传递给查询对象。然后将标量结果保存到变量(结果)中。如果结果是“”,那么你可以这样做,这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2016-08-21
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多