繁体   English   中英

如何调用存储过程从Java更新SqlTable的值

[英]How to call stored procedure which updates values of an SqlTable from java

我在sql中有一个具有以下属性的表

create table Product(
ID int identity primary key not null,
Name nvarchar(50) not null,
Price float not null
)

我创建了一个存储过程来插入值:

create proc spInsertNewProduct(
@name nvarchar(50),
@price float,
@qty int)
as
begin 
insert into Product values (@name,@price,@qty)
end

我从Java这样调用此方法:

public static void insertNewProduct(Product p){
    Connection connection = null;
    try {
    connection = DriverManager.getConnection(url);
    String SPsql = "exec[spInsertNewProduct] ?,?,?";
    PreparedStatement ps = connection.prepareStatement(SPsql);      
        ps.setEscapeProcessing(true);
        ps.setString(1, p.getProductName());
        System.out.println(p.getProductName());
        ps.setDouble(2, p.getPrice());
        System.out.println(p.getPrice());
        ps.setInt(3,p.getQty());
        System.out.println(p.getQty());
        ps.execute();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally{
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

然后我有这个存储过程,它更新了现有对象的值

create proc spUpdateProduct(
@id int,
@name nvarchar(50),
@price float,
@qty int)
as
begin
update Product
set Name = @name, Price = @price , Qty = @qty
where ID = @id
end

我尝试从Java调用此过程,但出现此错误: The index 0 is out of range. 网络上的主题对我没有太大帮助。 这是我的更新方法的代码。

    public static void updateProduct(Product p){
    Connection connection = null;
    try {
    connection = DriverManager.getConnection(url);
    String SPsql = "spUpdateProduct ?,?,?,?";
    PreparedStatement ps = connection.prepareStatement(SPsql);      
        ps.setEscapeProcessing(true);
        ps.setInt(0, p.getProductId());
        ps.setString(1,p.getProductName());
        ps.setDouble(2, p.getPrice());
        ps.setInt(3,p.getQty());
        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally{
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

参数索引从1而不是0开始:

    ps.setInt(1, p.getProductId());
    ps.setString(2,p.getProductName());
    ps.setDouble(3, p.getPrice());
    ps.setInt(4,p.getQty());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM