I can't select inner join data from MYSQL in Java.
I'm using this code in 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"));
}
This sintax works in MYSQL Workbench but in Java does not.
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
Can anyone help me?
I'll bet the exception is actually coming from this line:
System.out.println("ID da Despesa: " + rsTDP.getString("id_despesa") + " | Descrição: " + rsTDP.getString("descricao"));
I don't see the id_despesa column in the select statement and the ResultSet can only read columns from the select statement. So the rsTDP.getString("id_despesa") will throw a SQLException.
If you don't need the id_despesa column, then you can just leave it out of the println. Otherwise, you can change your SQL to this:
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";
With the column added to the query, then you will be able to get id_despesa out of the results.
Related
I am developing a java web service that is deployed in wildly. It is connected to a postgresql database.
In this database, I have a table called xx_activity. In it there is a column called "id", which is also the primary key.
Here is the query used to create the table:
CREATE TABLE xx_activity
(
id serial NOT NULL,
baseitemid integer
);
to connect to this table, I use the following java code:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid" +
"from xx_activity " +
"where \"id\" = ? ");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
However, when I call the method that includes this code, I get an error:
org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
This is confusing because I certainly have this column. i added escape characters as per this answer, but it did not solve the issue.
Also note that queries without the where clause, like:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity");
ResultSet rs = query.executeQuery();
work perfectly.
I have also tried without using escape characters but it gives the same error. I also checked in pgadmin and there is no trailing space in the column name, neither are there any upper case letters involved (in which case, the other select query shouldn't have worked?).
How can this be fixed?
Fixed this, the issue was a missing space. After the first line of the query, there needs to be a space as belows:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where \"id\" = ? ");
EDIT: escape charactors not needed for id; so final answer should be:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where id = ? ");
I'm trying to execute a SQL Server query using prepared statements:
PreparedStatement pst = con.prepareStatement("select * from openquery(SERVERNAME," +
"'Select r.A , r.B, c.C from Y r" +
"INNER JOIN X c" +
"ON r.RNID = c.RNID ')" +
"where c.C in ?");
pst.setString(1, data);
ResultSet rs = pst.executeQuery();
I get this error message:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot get the column information from OLE DB provider "MSDASQL" for linked server "SERVERNAME".
Update
After fixing the SQL statement to add the missing spaces
PreparedStatement pst = con.prepareStatement("select * from openquery(SERVERNAME, " +
"'Select r.A , r.B, c.C from Y r " +
"INNER JOIN X c " +
"ON r.RNID = c.RNID ') " +
"where c.C in ?");
I now get the error
com.microsoft.sqlserver.jdbc.SQLServerException: The multi-part identifier "c.C" could not be bound
The table aliases used within the OPENQUERY function are simply not available to the query that calls it. So, this will fail with 'multi-part identifier "c.ID" could not be bound':
SELECT *
FROM
OPENQUERY(ACCDBTEST, 'SELECT c.ID, c.LastName FROM Clients c')
WHERE c.ID = 1
but this works
SELECT *
FROM
OPENQUERY(ACCDBTEST, 'SELECT c.ID, c.LastName FROM Clients c')
WHERE ID = 1
as does this
SELECT *
FROM
OPENQUERY(ACCDBTEST, 'SELECT c.ID, c.LastName FROM Clients c') AS x
WHERE x.ID = 1
It's look like you need to make simple changes in your query.
You should try as I shown below then it will work.
You use below Four part table name in a distributed query and depending on your Java backend you need to omit the database name and schema.
PreparedStatement pst = con.prepareStatement("Select r.A , r.B, c.C from
[SERVERNAME].[databaseName].[dbo].Y r" +
"INNER JOIN [SERVERNAME].[databaseName].[dbo].X c" +
"ON r.RNID = c.RNID '" +
"where c.C in ?");
pst.setString(1, data);
ResultSet rs = pst.executeQuery();
this is what i got
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that
corresponds to your MySQl server version for the right syntax to use near 'order by idconsumo' at line 1
java.lang.IllegalArgumentException: Cannot set a null TableModel
code
sSQL = "select c.idconsumo,c.idreserva,c.idproducto,p.nombre,c.cantidad,c.precio_venta "
+ ",c.estado from consumo c inner join producto p on c.idproducto=p.idproducto"
+ " where c.idreserva = " + buscar +" order by idconsumo";
but still save it in the database. If i exit the app and open it again then the
record is added
First of all as Jon suggested, use the parametrized SQL.
You need to make few changes to the SQL as below:
"select c.idconsumo, c.idreserva, c.idproducto, p.nombre, c.cantidad, c.precio_venta, c.estado from consumo c inner join producto p on c.idproducto=p.idproducto where c.idreserva = " + buscar +" order by c.idconsumo";
Make sure if buscar is a variable and c.idreserva is non-int column then add single quotes around it like c.idreserva = '" + buscar +"' and order by c.idconsumo
Using prepared statement:
String sql = "select c.idconsumo, c.idreserva, c.idproducto, p.nombre, c.cantidad, c.precio_venta, c.estado from consumo c inner join producto p on c.idproducto=p.idproducto where c.idreserva = ? order by c.idconsumo";
PreparedStatement prepStmt = conn.prepareStatement(sql);
//if buscar is string type
prepStmt.setString(1, buscar);
ResultSet rs = prepStmt.executeQuery();
Query syntax error. Please check:
String sql = " select c.idconsumo,c.idreserva,c.idproducto,p.nombre,"
+" c.cantidad,c.precio_venta, c.estado "
+" from consumo c inner join producto p on "
+" c.idproducto=p.idproducto "
+" where c.idreserva ='" + buscar +"' order by c.idconsumo ";
PreparedStatement would be more accurate to use.
A PreparedStatement is a special kind of Statement object with some useful features. Remember, you need a Statement in order to execute either a query or an update. You can use a PreparedStatement instead of a Statement and benefit from the features of the PreparedStatement.
The PreparedStatement's primary features are:
Easy to insert parameters into the SQL statement. Easy to reuse the
PreparedStatement with new parameters. May increase performance of
executed statements. Enables easier batch updates.
String sql = " select c.idconsumo,c.idreserva,c.idproducto,p.nombre,"
+" c.cantidad,c.precio_venta, c.estado "
+" from consumo c inner join producto p on "
+" c.idproducto=p.idproducto "
+" where c.idreserva = ? order by c.idconsumo ";
PreparedStatement preStmt = conn.prepareStatement(sql);
preStmt.setInt(1, buscar);
ResultSet rs = preStmt.executeQuery();
I want to execute two queries in my PostgreSQL database via code java.
The first one create a temporary view and the second one get some data from this view.
This is my code:
String sql = "create or replace temp view recap as "
+ "select id_salarie, concat(nom, ' ', prenom) as np, hour_salary, id_chantier, id_activity, SUM(nb_heures) as s_hn, SUM(nb_heures_s) as s_hs, value_update, (hour_salary*SUM(nb_heures)) as cost_hn, ((hour_salary*value_update)*SUM(nb_heures_s)) as cost_hs "
+ "from pointage_full pf, salarie s, hs_increase hsi "
+ "where s.id = pf.id_salarie "
+ "and hsi.etat = 1 "
+ "and id_chantier = "+this.idProject+" and id_salarie <> id_chef "
+ "group by id_salarie, np, hour_salary, id_activity, id_chantier, value_update "
+ "order by id_salarie DESC;"
+ ""//=================execute the second query to get costs from created view===========================
+ "select id_activity, sum(cost_hn) as sm_cost_hn, sum(cost_hs) as sm_cost_hs, (sum(cost_hn)+sum(cost_hs)) as cost_activity "
+ "from recap "
+ "group by id_activity "
+ "order by id_activity asc;";
ResultSet res = state.executeQuery(sql);
while (res.next()) {
//---doing my stuff...
}
But I get this error:
org.postgresql.util.PSQLException: No results returned by the query.
You cannot execute more than one statement with a single executeXXX() call - especially not a DDL statement and a query.
But you don't need to create that (temporary) view in the first place. Also the order by inside the view is also useless as you are re-ordering the rows in the final statement again.
You can do what you want with one single statement:
select id_activity, sum(cost_hn) as sm_cost_hn, sum(cost_hs) as sm_cost_hs, (sum(cost_hn)+sum(cost_hs)) as cost_activity
from (
select id_salarie,
concat(nom, ' ', prenom) as np,
hour_salary,
id_chantier,
id_activity,
SUM(nb_heures) as s_hn,
SUM(nb_heures_s) as s_hs,
value_update,
(hour_salary*SUM(nb_heures)) as cost_hn,
((hour_salary*value_update)*SUM(nb_heures_s)) as cost_hs
from pointage_full pf, salarie s, hs_increase hsi
where s.id = pf.id_salarie
and hsi.etat = 1
and id_chantier = ?
and id_salarie <> id_chef
group by id_salarie, np, hour_salary, id_activity, id_chantier, value_update
) as recap
group by id_activity
order by id_activity asc;
You should also use a PreparedStatement instead of concatenating parameters into your SQL. If you have the above query in a String, you can do something like this:
PreparedStatement pstmt = connection.prepareStatement(QUERY);
pstmt.setInt(1, this.idProject);
ResultSet rs = pstmt.executeQuery();
while (rs.next()
{
// process result set
}
I'm pretty sure this will be faster than first creating a temp view and then querying that.
I don`t get it. I created a query where made some joins of two tables in SQLite. In my SQLite Browser there is all ok and the columns are displayed correctly. But when I call executeQuery, I always get the error:
[SQLITE_ERROR] SQL error or missing database (no such column: td.value)
Here is my statement:
private static final String QUERY_ENDUSES = "SELECT td.Value Value, reportn.Value ReportName, fs.Value ReportForString, tn.Value TableName, rn.Value RowName, cn.Value ColumnName, u.Value Units, RowId "
+ "FROM TabularData td"
+ "INNER JOIN Strings reportn ON reportn.StringIndex=td.ReportNameIndex "
+ "INNER JOIN Strings fs ON fs.StringIndex=td.ReportForStringIndex "
+ "INNER JOIN Strings tn ON tn.StringIndex=td.TableNameIndex "
+ "INNER JOIN Strings rn ON rn.StringIndex=td.RowNameIndex "
+ "INNER JOIN Strings cn ON cn.StringIndex=td.ColumnNameIndex "
+ "INNER JOIN Strings u ON u.StringIndex=td.UnitsIndex WHERE report n.StringTypeIndex=1 AND fs.StringTypeIndex=2 AND tn.StringTypeIndex=3 AND rn.StringTypeIndex=4 AND cn.StringTypeIndex=5 AND u.StringTypeIndex=6 "
+ "AND td.ReportNameIndex = 1 AND tn.StringIndex = 59;";
If I substitute the statement through Select td.value from TabularData td , then all is OK!
Can anybody help me?
You're missing a space between td in the FROM clause, and the first INNER.