有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在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.web上的主题对我帮助不大。这是我的更新方法的代码

    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) 个答案

  1. # 1 楼答案

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

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