[英]How to call stored procedure which updates values of an SqlTable from java
I have a table in sql with the following attributes 我在sql中有一个具有以下属性的表
create table Product(
ID int identity primary key not null,
Name nvarchar(50) not null,
Price float not null
)
I created a stored procedure to insert values: 我创建了一个存储过程来插入值:
create proc spInsertNewProduct(
@name nvarchar(50),
@price float,
@qty int)
as
begin
insert into Product values (@name,@price,@qty)
end
I call this method from java like this: 我从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();
}
}
}
Then I have this stored procedure which updates the values of an existing object 然后我有这个存储过程,它更新了现有对象的值
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
I tried to call this procedure from java and but i get this error: The index 0 is out of range.
我尝试从Java调用此过程,但出现此错误:
The index 0 is out of range.
The topics on web haven't helped me very much. 网络上的主题对我没有太大帮助。 This the code for my update method.
这是我的更新方法的代码。
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();
}
}
}
The parameter index starts at 1 not 0: 参数索引从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.