SQL如何用一条SQL语句更新表行

Posted

技术标签:

【中文标题】SQL如何用一条SQL语句更新表行【英文标题】:SQL how to update table rows with one SQL statement 【发布时间】:2012-03-16 12:09:35 【问题描述】:

我有一个包含 2 列的表,用于在 Oracle 数据库中存储应用程序设置。这是一个基本的例子:

我想创建一个 java 方法,用准备好的语句更新值。

示例代码:

更新代码

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();

                  

           

我知道这条 SQL 语句是错误的。写SQL语句的正确方法是什么?

最好的祝愿 彼得

P.S 更新代码后我得到这个错误堆栈:

javax.faces.el.E​​valuationException: 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)

原因: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

【问题讨论】:

【参考方案1】:

正确的语法应该是这样的:

UPDATE GLOBALSETTINGS 
   SET settingValue = case 
                        when settingName = 'SessionTTL' = then ? 
                        when settingName = 'MaxUsersActive' = then ? 
                        else settingValue
                      end
WHERE settingName in ('SessionTTL', 'MaxUsersActive');

但我不建议这样做,因为它会使您的代码难以阅读和维护。

运行两个更新语句可能会更好:

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();

如果您想保存一些到数据库的往返,您可以将其作为批处理语句运行:

pstmt.setString(1, "40");
pstmt.setString(2, "SessionTTL");
pstmt.addBatch();

pstmt.setString(1, "20");
pstmt.setString(2, "MaxUsersActive");
pstmt.addBatch();

pstmt.executeBatch();

这会将两个语句“一次性”发送到数据库服务器。

注意:我假设 settingName 是唯一的。

【讨论】:

你确定第一个例子是正确的吗?我再次得到 java.sql.SQLSyntaxErrorException: ORA-00905: missing keyword。我如何在 sqlplus 中运行它来测试它?如果它以这种方式在 sqlplus 中运行,我会在命令行得到错误:3 列:56 错误报告:SQL 错误:索引处缺少 IN 或 OUT 参数:: 1 我的示例是 Java 代码,SQL 旨在作为准备好的语句运行(就像您的示例一样)。您不能在 SQL*Plus 中使用? 运行这样的 SQL 语句。您需要用实际值替换它们。 据我所知,没有交互式 SQL 工具可以处理准备好的语句。您必须用实际值替换问号。如果您对 Java 解决方案不感兴趣,而只是对简单的 SQL 解决方案感兴趣,我不明白为什么要发布所有 Java 代码。 错误很明显不是吗?您没有名为 SETTINGNAME 的列。显然您没有向我们展示正确的表定义。【参考方案2】:
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);

您可以查看tutorials from oracle

【讨论】:

这很可能还需要一个WHERE 子句 我想添加它,但我查看了彼得的问题要求。 是的,这将更新所有行并覆盖所有内容。所以提出问题的人要小心。【参考方案3】:
SQL_Statement = "UPDATE GLOBALSETTINGS SET (SettingName = ?, SettingValue = ?)";

【讨论】:

我按照您的建议更新了代码,但现在我收到此错误消息:javax.faces.el.E​​valuationException: java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis

以上是关于SQL如何用一条SQL语句更新表行的主要内容,如果未能解决你的问题,请参考以下文章

如何用SQL语句向一个表中插入多行记录

如何用SQL语句向一个表中插入多行记录

如何用sql语句将一列多行数据拼接逗号隔开形成一条记录

如题:如何用一条SQL语句按输入的参数进行判断执行查询数据

如何用sql语句查询:在一个表中存在而另一个表中不存在的第一条记录?

若何用一条sql语句查看所有表的注释?