首页 > 解决方案 > 我有这个错误:java.sql.SQLException:Java 应用程序中的列名无效

问题描述

我构建了一个应用程序来计算表格中的一些税表,并且必须在另一个表格中插入数字。当我计算第一个表中的税表时,我使用以下 sql 查询:

select count(distinct cui) from dec_declaratii where id > 142321849 and 
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern 
in ('DUK_VLD', 'GEN_MSJ')";

当我从 Oracle Toad 运行它时它可以工作,但是当我把它放在 java 中并尝试使用 rs.getString("count(distinct cui)") 得到结果时,它给了我这个错误:java.sql.SQLException: Invalid column姓名

为什么会这样?

我该怎么做才能让它发挥作用?

我尝试用大写字母写 count(distinct cui),如果我写 count(*),它可以工作,但我需要不同数量的税表。

public class Baza {

int idmin = 142321849;
int rezultat = 391320;

    String host = "xxx";
    String user = "xxx";
    String pass = "xxx";
    String user2 = "xxx";
    String pass2 = "xxx";

    String host2 = "xxx";
    String nr = "0";
public void conectare() {

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host, user, pass);
    Statement st = con.createStatement();
    String sql = "select count(distinct cui) from dec_declaratii where id 
> 142321849 and tip_declaratie='D212' and anul_duk>=2019 and 
cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')";
    ResultSet rs = st.executeQuery(sql);
    while(rs.next()) {
       nr = rs.getString("count(DISTINCT CUI)");
       System.out.println(nr);
    }
    }catch(Exception e) {System.out.println(e);}
    int nr2 = Integer.parseInt(nr);

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host2, user2, pass2);
     Statement st = con.createStatement();
     String sql = "update nr_tot_dec_212 set nr_dec='"+nr+"', data=sysdate 
where id=1";
     st.executeUpdate(sql);


    }catch(Exception e) {System.out.println(e);}
 }

}

我想得到查询的结果: select count(distinct cui) from dec_declaratii where id > 142321849 and tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')"; 在Java 变量。它给了我这个错误:java.sql.SQLException: Invalid column name

标签: javasqloracle

解决方案


使用别名命名您的计数列

select count(distinct cui) as cnt from dec_declaratii where id > 142321849 and 
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern 
in ('DUK_VLD', 'GEN_MSJ')";

推荐阅读