首页 > 解决方案 > 使用 C# 在 ASP.NET 中检查 SQL Server 表中的列值是否为空

问题描述

我正在使用 C# 在 ASP.NET 中工作,我正在努力完成这段代码。

我的页面上显示了一个下拉列表,用户可以在该下拉列表中对页面上的一本书进行评分。

首先,我想检查用户是否已经给出了评分(如果评分列有值)。

如果它没有值,则用户可以通过从下拉列表中进行选择来进行评级。

到目前为止,这是我的代码。我不确定在 if() 中写什么

// CRUD statement 
SqlCommand cmdCheck = ratingconn.CreateCommand();
cmdCheck.CommandText = "SELECT bookRating FROM tbl_ratingInfo WHERE userID = '" + Session["userID"] + "'";

if()
{
    // reading the information from the database
    SqlDataReader reader = cmdCheck.ExecuteReader();

    if (reader.Read())
    {
        // setting the label text values
        ddl_BookName.Text = reader.GetInt32(0).ToString();
    }
}
else
{
    // creating CRUD statement
    SqlCommand cmdRating = ratingconn.CreateCommand();
    cmdRating.CommandText = "INSERT INTO tbl_ratingInfo (bookRating) VALUES('"
                    + ddl_Rating.Text + "') WHERE userID = " + Session["userID"] + "' ";
}

这是我的数据库。该表是 SQL 代码中的交集表。

-- Create the rating info table
CREATE TABLE tbl_ratingInfo
(
    -- Add Foreign Keys from members and class tables
    bookTitle VARCHAR (100) NOT NULL REFERENCES tbl_bookInfo(bookTitle),
    userID INT NOT NULL REFERENCES tbl_userInfo(userID),
    bookRating INT NOT NULL DEFAULT 5 CHECK (bookRating <= 5),
    -- Composite Primary Key
    PRIMARY KEY (bookTitle, userID)
)
GO

标签: c#asp.netsql-server

解决方案


内联查询不是一个好习惯。请改用存储过程。

您可以在 if 条件中使用 SqlDataReader 的 HasRows:

SqlCommand cmdCheck = ratingconn.CreateCommand();
            cmdCheck.CommandText = "SELECT bookRating FROM tbl_ratingInfo WHERE userID = '" + Session['userID'] + "'";

            //reading the information from the database
            SqlDataReader reader = cmdCheck.ExecuteReader();

            if (reader.HasRows) // true if the SqlDataReader contains one or more rows otherwise false.
            {
                if (reader.Read())
                {
                    // setting the label text values
                    ddl_BookName.Text = reader.GetInt32(0).ToString();
                }
            }
            else
            {
                // creating CRUD statement
                SqlCommand cmdRating = ratingconn.CreateCommand();
                cmdRating.CommandText = "INSERT INTO tbl_ratingInfo (bookRating) VALUES('"
                                + ddl_Rating.Text + "') WHERE userID = " + Session["userID"] + "' ";
            }

推荐阅读