如何从数据库中减去 [英] how to subtract from database

查看:106
本文介绍了如何从数据库中减去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理项目,例如admin的数量为coloumn为10然后当客户输入9个数量时,它必须在admin中更新剩余的数量是1我的意思是它必须被减去..你能告诉我代码在使用数据库连接的servlet中。

i am working on project where for example admin has quantity coloumn as 10 then when customer enters 9 quantity it has to update in admin that quantity left over is 1 i mean it has to be subtracted..can you tell me the code in servlets using database connection.

推荐答案

首先不要将SQL构建为字符串,这只是要求麻烦。



尝试这样的事情:



Firstly do not build the SQL as a string, that is just asking for trouble.

Try something like this:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UpdateInventory
{
    // set this to some connection protocol like "jdbc:sqlserver://"
    private final String protocol;
    // set this to the name of your database
    private final String dbName;
    private final String username;
    private final String password;
    private final Connection connection;

    public UpdateInventory(String protocol,
            String dbName,
            String username,
            String password)
                throws SQLException
    {
        this.protocol = protocol;
        this.dbName =dbName;
        this.username = username;
        this.password = password;
        this.connection = DriverManager.getConnection(protocol + dbName,
                username, password);
    }

    public int update(String item, int quantity)
            throws SQLException
    {
        // validate
        if (item == null ||
                "".equals(item))
        {
            throw new IllegalArgumentException("Item must be set");
        }
        if (quantity <= 0)
        {
            throw new IllegalArgumentException("Quantity must be greater than zero");
        }

        PreparedStatement updateInventory = this.connection.prepareStatement(
                "UPDATE inventory SET quantity = (quantity - ?) WHERE item = ?");

        updateInventory.setInt(1, quantity);
        updateInventory.setString(2, item);
        //there are similar methods for other SQL types in PerparedStatement

        return updateInventory.executeUpdate();//returns the number of rows changed
    }
}


这篇关于如何从数据库中减去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆