无法从MYSQL中选择内部联接数据

时间:2017-08-25 13:52:39

标签: java mysql jdbc

我无法在Java中从MYSQL中选择内部联接数据。

我在Java中使用此代码:

Class.forName("com.mysql.jdbc.Driver");
Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/despesas?useSSL=true", "root", "local"); 
Statement comando = conexao.createStatement();
String sqlInsert;
ResultSet rsTDP;
sqlInsert = "select id_historico, tipos_de_despesas.descricao, dt_desp, valor_despesa from tipos_de_despesas INNER JOIN historico_despesas ON tipos_de_despesas.id_despesa=historico_despesas.id_despesa ORDER BY dt_desp desc";
rsTDP = comando.executeQuery(sqlInsert);
while(rsTDP.next()){
    System.out.println("ID da Despesa: " + rsTDP.getString("id_despesa") + " | Descrição: " + rsTDP.getString("descricao"));
}

这个sintax在MYSQL Workbench中有效但在Java中却没有。

SELECT id_historico, tipos_de_despesas.descricao, dt_desp, valor_despesa from tipos_de_despesas INNER JOIN historico_despesas ON tipos_de_despesas.id_despesa=historico_despesas.id_despesa ORDER BY dt_desp desc

This is result in Workbench

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

我打赌这个例外实际上来自这条线:

System.out.println("ID da Despesa: " + rsTDP.getString("id_despesa") + " | Descrição: " + rsTDP.getString("descricao"));

我没有在select语句中看到id_despesa列,ResultSet只能读取select语句中的列。因此rsTDP.getString("id_despesa")会抛出SQLException

如果您不需要id_despesa列,则可以将其从println中删除。否则,您可以将SQL更改为:

sqlInsert = "select tipos_de_despesas.id_despesa, id_historico, tipos_de_despesas.descricao, dt_desp, valor_despesa from tipos_de_despesas INNER JOIN historico_despesas ON tipos_de_despesas.id_despesa=historico_despesas.id_despesa ORDER BY dt_desp desc";

将列添加到查询中,您就可以从结果中获取id_despesa