简体   繁体   English

JDBC PreparedStatement,如何选择和插入?

[英]JDBC PreparedStatement, how to select and insert?

I'm trying to execute stored procedure via JDBC, which has simple structure: 我正在尝试通过JDBC执行存储过程,它具有简单的结构:

ALTER PROCEDURE test
AS BEGIN
SELECT ...
INSERT ...
END

The problem is that insert is not happened . 问题是插入没有发生 When I execute this procedure in management studio, then it's all right. 当我在管理工作室执行此程序时,它就可以了。

String query = "EXEC test";
PreparedStatement st = conn.prepareStatement(query);
st.execute();
ResultSet rs = st.getResultSet(); //result set is correct
int count = st.getUpdateCount(); //returns -1

Any ideas? 有任何想法吗? Thanks 谢谢

Since its a procedure you're trying to call, you need to use a CallableStatement . 由于它是您尝试调用的过程,因此您需要使用CallableStatement

The interface used to execute SQL stored procedures. 用于执行SQL存储过程的接口。

CallableStatement callableStatement = conn.prepareCall(query);

Also, your query needs to be 此外,您的查询需要

String query = "{call test}"; 
// exec is used to execute the procedure from the sql console as such
// To execute a procedure using the java code, use call proc.

you should be using a callable statement instead of prepared statement 你应该使用可调用语句而不是预备语句

CallableStatement cstmt = null;
try {
   String SQL = "{call procedureName}";
   cstmt = conn.prepareCall (SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

you can try change the value of query to String query = "{call test()}" and then you can use 您可以尝试将查询的值更改为String query = "{call test()}"然后您可以使用

CallableStatement cs = connection.prepareCall(query); CallableStatement cs = connection.prepareCall(query);

cs.execute(); cs.execute();

you can need commit to view your changes in the database. 您可能需要提交以查看数据库中的更改。

conn.commit(); conn.commit();

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

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