Java SQL如何用一条SQL语句更新表行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9736960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL how to update table rows with one SQL statement
提问by Peter Penzov
I have a table with 2 columns for storing application settings in Oracle database. This is a just basic example:
我有一个包含 2 列的表,用于在 Oracle 数据库中存储应用程序设置。这是一个基本的例子:
I want to create a java method which updates the values with prepared statement.
我想创建一个 java 方法,它用准备好的语句更新值。
Example code:
示例代码:
UPDATED CODE
更新代码
public void updateDBSettings() throws SQLException {
String SQL_Statement = null;
if (ds == null) throw new SQLException();
Connection conn = ds.getConnection();
if (conn == null) throw new SQLException();
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQL_Statement = "UPDATE GLOBALSETTINGS SET (SettingName = ?, SettingValue = ?)";
PreparedStatement updateQuery = conn.prepareStatement(SQL_Statement);
updateQuery.setString(1, "20");
updateQuery.setString(2, "40");
updateQuery.executeQuery();
conn.commit();
committed = true;
} finally {
if (!committed) conn.rollback();
}
}
finally {
conn.close();
}
}
I know that this SQL statement is wrong. What is the proper way to write the SQL statement?
我知道这个 SQL 语句是错误的。写SQL语句的正确方法是什么?
Best wishes Peter
最好的祝福彼得
P.S
After updating the code I get this error stack:
P.S
更新代码后,我收到此错误堆栈:
javax.faces.el.EvaluationException: java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
javax.faces.el.EvaluationException: java.sql.SQLSyntaxErrorException: ORA-00907: 缺少右括号
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
引起:java.sql.SQLSyntaxErrorException:ORA-00907:缺少右括号
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1044)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1329)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
at com.sun.gjc.spi.jdbc40.PreparedStatementWrapper40.executeQuery(PreparedStatementWrapper40.java:642)
at com.DX_57.SM_57.Application.updateDBSettings(Application.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:528)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257)
at com.sun.el.parser.AstValue.invoke(AstValue.java:248)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 32 more
采纳答案by a_horse_with_no_name
The correct syntax would be something like this:
正确的语法是这样的:
UPDATE GLOBALSETTINGS
SET settingValue = case
when settingName = 'SessionTTL' = then ?
when settingName = 'MaxUsersActive' = then ?
else settingValue
end
WHERE settingName in ('SessionTTL', 'MaxUsersActive');
However I would not recommend this because it makes your code hard to read and maintain.
但是我不推荐这样做,因为它会使您的代码难以阅读和维护。
You are probably better off running two update statements:
您最好运行两个更新语句:
String sql =
"UPDATE GLOBALSETTINGS " +
" SET settingValue = ? " +
"WHERE settingName = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "40");
pstmt.setString(2, "SessionTTL");
pstmt.executeUpdate();
pstmt.setString(1, "20");
pstmt.setString(2, "MaxUsersActive");
pstmt.executeUpdate();
If you want to save some roundtrips to the database, you can run this as a batched statement:
如果您想将一些往返保存到数据库,您可以将其作为批处理语句运行:
pstmt.setString(1, "40");
pstmt.setString(2, "SessionTTL");
pstmt.addBatch();
pstmt.setString(1, "20");
pstmt.setString(2, "MaxUsersActive");
pstmt.addBatch();
pstmt.executeBatch();
This sends two statements in "one go" to the database server.
这将“一次性”发送两个语句到数据库服务器。
Note: I assume that settingName is unique.
注意:我假设 settingName 是唯一的。
回答by tusar
SQL_Statement = "UPDATE GLOBALSETTINGS SET (SettingName = ?, SettingValue = ?)";
回答by Nandkumar Tekale
String sqlStatement =
"update GLOBALSETTINGS " +
"set SettingName = ?, " +
"SettingValue = ?" +
"where id = ?"; // You have to put where condition here, otherwise all rows will get affected. I assume your serch-key-column as id. Change 'id' according to your table
PreparedStatement updateQuery = con.prepareStatement(sqlStatement);
updateQuery.setString(1, "20");
updateQuery.setString(2, "40");
updateQuery.setString(3, applicationSettingId);
You can check out tutorials from oracle