我目前正在制作一个由Access数据库支持的ASP网站。在网站上,我想让玩家购买一些商品。他们有两种形式的货币 - 宝石和草药。
当玩家购买物品时,我想做三个单独的动作 -
ItemPlayerConnection
表因此,我正在尝试构建3个不同的查询 - 第一个应该是这样的:
UPDATE ItemPlayerConnection
SET Inventory=TRUE
WHERE
Player=PlayerNameHere
AND Item=ItemIDHere
将商品从商店移至库存。第二个和第三个是相似的,唯一的区别是宝石和草药 - 它们应该是这样的:
UPDATE Player
SET CurrencyNameHere=(CurrencyNameHere-ItemPriceHere)
WHERE
Owner=PlayerNameHere
所以我尝试了以下代码:
static public void Purchase(string player, int itemID, int herbPrice, int gemPrice)
{
OleDbCommand command1 = GenerateConnection(
"UPDATE ItemPlayerConnection SET Inventory=TRUE WHERE Player=@player AND Item=@itemID");
command1.Parameters.AddWithValue("@player", player);
command1.Parameters.AddWithValue("@itemID", itemID);
OleDbCommand command2 = GenerateConnection(
"UPDATE Player SET Herbs=(Herbs-@herbPrice) WHERE Owner=@player");
command2.Parameters.AddWithValue("@herbPrice", herbPrice);
command2.Parameters.AddWithValue("@player", player);
OleDbCommand command3 = GenerateConnection(
"UPDATE Player SET Gems=(Gems-@gemPrice) WHERE Owner=@player");
command3.Parameters.AddWithValue("@gemPrice", gemPrice);
command3.Parameters.AddWithValue("@player", player);
command3.ExecuteNonQuery();
command2.ExecuteNonQuery();
command1.ExecuteNonQuery();
}
通过断点,我看到了查询 - 它们看起来很好,但是,虽然草药和宝石已经更换,但物品却没有从商店传递到库存。这些没有引起语法错误 -
我的错误是什么?
答案 0 :(得分:1)
您的代码似乎很好,您可能遇到了业务错误,但我想帮助解决其他问题:
AddWithValue
只需要参数名称和值,而不是类型; 您修改的代码将是:
static public void Purchase(string player, int itemID, int herbPrice, int gemPrice)
{
OleDbCommand command1 = GenerateConnection(
"UPDATE ItemPlayerConnection SET Inventory=TRUE WHERE Player=@player AND Item=@itemID");
command1.Parameters.AddWithValue("@player", player);
command1.Parameters.AddWithValue("@itemID", itemID);
OleDbCommand command2 = GenerateConnection(
"UPDATE Player SET Herbs=(Herbs-@herbPrice) WHERE Owner=@player");
command2.Parameters.AddWithValue("@herbPrice", herbPrice);
command2.Parameters.AddWithValue("@player", player);
OleDbCommand command3 = GenerateConnection(
"UPDATE Player SET Gems=(Gems-@gemPrice) WHERE Owner=@player");
command3.Parameters.AddWithValue("@gemPrice", gemPrice);
command3.Parameters.AddWithValue("@player", player);
command3.ExecuteNonQuery();
command2.ExecuteNonQuery();
command1.ExecuteNonQuery();
}
答案 1 :(得分:0)
显然你们没有机会,这是我的坏事。另一个由按钮单击触发的函数发送了ItemID - 显然,我使用了错误的方法来获取它,并且我发送了错误值 - 因此,查询已执行,语法正确,但由于没有项目我发送的ID - 什么也没发生。我通过设置断点并查看参数值来计算出来。现在让我们来一杯,你和我,for many stupid mistakes. :)
答案 2 :(得分:-5)
SqlConnection con = new SqlConnection("");
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cmd = new SqlConnection();
DataTable dt = new DataTable();
da.SelectCommand = con.CreateCommand();
da.SelectCommand.CommandText="UPDATE ItemPlayerConnection SET Inventory=TRUE WHERE Player="+player+" AND Item="+itemID);
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(dt);