如何调用从java更新SqlTable值的存储过程
我在sql中有一个具有以下属性的表如何调用从java更新SqlTable值的存储过程,java,sql,sql-server,stored-procedures,Java,Sql,Sql Server,Stored Procedures,我在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 Produc
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调用此过程,但出现了以下错误:索引0超出范围。
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开始,而不是从0开始:
ps.setInt(1, p.getProductId());
ps.setString(2,p.getProductName());
ps.setDouble(3, p.getPrice());
ps.setInt(4,p.getQty());