Javaweb项目sql语句参数问题解决及实例讲解

做课程设计时候,由于要实现”商品加入购物车后库存自动减少”功能,写了个函数update_stock。

里面有用到sql语句,同时函数参数包括(num,id),即购买数量和商品id

第一次写的sql语句如下:

string sql = “update items set number=number-num where id=’id’;”;? (这是错误的)

(number为表items里面的属性,表示库存)

后来发现函数执行后,items表库存并未改变。

后搜索原因:

string sql=” ” 的形式 引号内只能是固定值。 例如:

string sql=”update items set number=1 where id=’3′;”;

解决方法:

1) string.format()方法

string sql=string.format("update items set number=number-%d where id=%d;",num,id);

2) +号连接(相当于字符串拼接)

/* string sql="update items set "number=number-"+num+"where id="+id;"; */
(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐