c# - 使用 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
解决方案
内联查询不是一个好习惯。请改用存储过程。
您可以在 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"] + "' ";
}
推荐阅读
- asciidoc - asciidoc asciidoctor 包括 adocs 及其图像
- javascript - Infinite animation opacity not works for several elements
- annotations - cdi @Startup annotated @PostConstruct method not called
- node.js - SMTP Server in a cloud function, possible?
- javascript - adonis 迁移:在 Gitlab 部署中运行失败
- sql - Postgresql以FIFO方式限制表行
- javascript - 在反应的功能组件中实现 onKeyPress
- amazon-ec2 - 将快照包含在根目录上的多个 ebs 卷合并为一个
- node.js - SQL Server:无法通过 ODBC 驱动程序连接
- c++ - Scanf 从标准输入浮动,由字符“e”分隔