gpt4 book ai didi

c# - ASP.NET SQL 问题和代码帮助

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:55 25 4
gpt4 key购买 nike

我编写了下面的代码,用于将产品添加到购物篮,然后输出它们以及向服务器发出多个请求以插入和选择数据。

我昨天发布了一个关于将 SQL 命令的结果分配给变量的问题,但似乎没有任何效果,可能是由于我编写的代码,如果有解决方案,我将不胜感激。

无论如何,还有什么可以简化我似乎正在制作的 SQL 命令

我知道 SQL 注入(inject)攻击的漏洞,这只是一个 Uni 项目,我怀疑讲师是否知道这些漏洞!不过,一旦我的基本功能正常工作,我就会解决这些问题:)

string CurrentUser="";
if (User.Identity.IsAuthenticated) {
CurrentUser = Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString(); //Get the current user
}

//Insert the current user into the DB
BasketPage.InsertCommand = "INSERT INTO tblBasket(UserID, CreatedDate) VALUES ('" + CurrentUser + "'), CONVERT (DATETIME, '2010-11-20 00:00:00', 102))";

//Select the Basket ID for this user which is an auto increment hence why I inserted the user first
BasketPage.SelectCommand = "SELECT BasketID FROM tblBasket WHERE (UserID = '" + CurrentUser + "')";

var basketID= //Result of the previous select command

if (Session["CartSess"] != null) {
List<BasketClass> cart = (List<BasketClass>)Session["CartSess"];

foreach (BasketClass BookID in (List<BasketClass>)Session["CartSess"]) {
BasketPage.InsertCommand = "INSERT INTO tblBasketDetails(BasketID, BookID) VALUES (" +
basketID + "," + BookID + ")"; //Inserts each book into the DB and the Basket ID
BasketPage.Insert();
}
}

//Outputs the Basket for the current user
BasketPage.SelectCommand = "SELECT tblBasket.UserID, tblBasket.BasketID, tblBooks.Title, tblBasketDetails.Quantity " +
"FROM tblBasket " +
"INNER JOIN tblBasketDetails ON tblBasket.BasketID = tblBasketDetails.BasketID " +
"INNER JOIN tblBooks ON tblBasketDetails.BookID = tblBooks.BookID " +
"WHERE (tblBasket.UserID = '" + CurrentUser + "')";

最佳答案

线上:

BasketPage.InsertCommand = "INSERT INTO tblBasket(UserID, CreatedDate) VALUES ('" + CurrentUser + "'), CONVERT (DATETIME, '2010-11-20 00:00:00', 102))"; //Insert the current user into the DB

将“SomeValue”替换为您的 CurrentUser 变量,您的 SQL 是:

INSERT INTO tblBasket(UserID, CreatedDate) 
VALUES ('SomeValue'), CONVERT (DATETIME, '2010-11-20 00:00:00', 102))

尝试在 SQL 窗口中运行它。在 SQL Server 中,您将获得:

There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

您的问题出在 VALUES LINE 上的第一个闭括号上。代码应该是:

INSERT INTO tblBasket(UserID, CreatedDate) 
VALUES ('SomeValue', CONVERT (DATETIME, '2010-11-20 00:00:00', 102))

作为一般性建议,请在将查询作为代码的一部分运行之前尝试独立测试它们。

抛开您提到的 SQL 注入(inject)问题,这是将所有代码移动到存储过程并使用代码中的参数调用它的另一个原因。

关于c# - ASP.NET SQL 问题和代码帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4365316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com