Using a Java method in an SQL Query - java

I made a program to parse an XML file with, and now I want to put the data in a database,
a PostgreSQL database. However, I cannot use
executeUpdate(INSERT INTO Titles(name) VALUES (parseTitles())),
since it wants a boolean. The string that comes out of the function looks like this:
'a','b','c','d'
Is there a way to solve this, or am I bound to put all the data in manually?

java runs first and then the SQL statement is sent to the db to be executed.
You probably need something like this to produce the right sql statement:
executeUpdate( "INSERT INTO Titles(name) VALUES (" + parseTitles() + ")" );

Related

Get results as CSV from postgresql using hibernate

I execute a query which should return the results as a CSV to the STDOUT.
When I execute my query in the pgAdmin I successfully get results.
However when I execute the same query using hibernate I gets the following exception:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
I mustn't show the tables structure but I know that the sql is fine(I've copied the entire content of "sql" then I execute it in pgAdmin); The query looks like:
String sql = "COPY (" + sqlQuery + ") TO STDOUT WITH CSV";
Then I execute it as the following:
Query query = getEntityManager().createNativeQuery(sql);
Object result = query.getSingleResult(); // I also tried the other get results method...(`getFirstresult()` has returned 0)
In any related questions I have found, I saw that the OP put the csv into a file instead of stdout.
Is it possible to return csv result using hibernate?
Thanks in advance!
AFAIK, COPY is not supported natively by PostgreSQL JDBC driver (last tested on postgresql-9.4.1208.jre7). Thus, Hibernate can not run the command.
If you really need to use COPY you should consider a CopyManager: how to copy a data from file to PostgreSQL using JDBC?
But personally, I would advocate you change your approach. Loading data with COPY looks like a kind of a hack to me.
You can have this done with univocity-parsers using two lines of code. You just need to get a resultset from your query and do this:
CsvRoutines routines = new CsvRoutines();
routines.write(resultset, new File("/path/to/output.csv"), "UTF-8");
The write() method takes care of everything. The resultset is closed by the routine automatically.

JDBC throws MySQL syntax Exception, despite valid query

Hello helpful folks,
I've a small part in an application which creates a new db schema based on a mysqldump.
The relevant part looks like this:
log.info("= setup basic database");
// Execute each command in the dump
for (String query : dump.split(";")) {
statement.execute(query);
}
This works fine but some statements just break with something like
com.mysql.jdbc.exceptions.jdbc4.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 ''ot_subtotal.php' at line 1
The query in this case is
INSERT INTO `configuration` VALUES (194,'MODULE_ORDER_TOTAL_INSTALLED','ot_subtotal.php;ot_discount.php;ot_coupon.php;ot_shipping.php;ot_cod_fee.php;ot_gv.php;ot_subtotal_no_tax.php;ot_tax.php;ot_total_netto.php;ot_total.php',6,0,NULL,'2016-06-17 15:27:24',NULL,NULL);
If I replace the string "'ot_subtotal.php;ot_discount.php;ot_coupon.php;ot_shipping.php;ot_cod_fee.php;ot_gv.php;ot_subtotal_no_tax.php;ot_tax.php;ot_total_netto.php;ot_total.php'" with something like "hello world" it works and breaks at a another query later on.
The thing is, I'm able to import the dump via the terminal command "mysql ... < dump.sql" without a problem.
Any ideas?
This is happening because of
for (String query : dump.split(";")) {
statement.execute(query);
}
You are splitting at ; which result in incomplete queries.
For example:
INSERT INTO `configuration` VALUES (194,'MODULE_ORDER_TOTAL_INSTALLED','ot_subtotal.php;ot_discount.php;ot_coupon.php;ot_shipping.php;ot_cod_fee.php;ot_gv.php;ot_subtotal_no_tax.php;ot_tax.php;ot_total_netto.php;ot_total.php',6,0,NULL,'2016-06-17 15:27:24',NULL,NULL);
Above query after split at ; will be
INSERT INTO `configuration` VALUES (194,'MODULE_ORDER_TOTAL_INSTALLED','ot_subtotal.php
Which is incorrect.
Instead of
dump.split(";")
Use
dump.split(";\n")
If you created the dump file in normal way.

UCASE and UPPER sql functions

I am trying to do the following query:
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
in an example of usage of an servlet to access to a database
But I am getting the error message:
Excepcion java.sql.SQLSyntaxErrorException: ORA-00904: "UCASE": invalid identifier
On the other hand, when I use the UPPER sql function, the example works but the results do not show the values of the LASTNAME column in uppercase. I do not understand what happens.
You're just comparing the upper case values, but you're selecting the actual values with select *
to get the uppercase name in your resultset you need to use UPPER in your select list, not UCASE, like this:
String query = "SELECT UPPER(LAST_NAME) AS UPPERNAME, * FROM EMP WHERE UPPER(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
What your code is doing here is building a query string named query. Once query is complete, it will be sent to the database for parsing and running.
When you are building a query to the database, you have to use the built-in database functions for the part of the query that the database is going to parse and run. So, in your example, Java is doing toUpperCase on lastName and then putting that literal into the query string that will go to the database. UPPER(LAST_NAME) is going into the query string as is, it will get passed to the database just like that and run by the database. So it needs to be a function that the database can parse and run: an Oracle function, not a Java function.
UCASE is a DB2 function & not Oracle. For Oracle, you need to use UPPER .
Second part of your question is already answered by James Z.
Having said that, I am answering because previous answers didn't pointed out SQL injection problem with the way you listed your query.
Make it a habit to always execute parametrized queries with jdbc & not by directly appending values to query string.
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) LIKE ? ";
Your parameter would be - lastName.toUpperCase()+"%"
SQL Injection

Java sql char prepared statement

I have a problem with a prepared statements with a char(3) parameter.
When I put the string directly into the SQL string I have no problem and the result set is correct, here's an example:
WHERE REQ.SERVICEID = 'SIN'
However, when I try to use a prepared statement in a safer way, I obtain no data!
The code is below:
" WHERE REQ.SERVICEID = ? "
and then
statement.setString(1,"SIN");
What is the problem?
Make sure you are using utf-8, i.e. with mysql:
jdbc:mysql://localhost:3306/db_name?characterEncoding=UTF-8
For other databases, there should be analog options.

"ResultSet is from UPDATE: No Data" received from Java application

I am trying to use a Java application (which I do not have the source code for) to output the results of a call to a stored procedure into a text file.
This file works for other similar stored procedures in the system, but I can't seem to get it to produce anything for my new text file other than this exception:
ResultSet is from UPDATE: No Data
I've simplified the body of the stored procedure to a simple select 'Hello World!' and even that doesn't seem to be able to be written out.
Is there anything I can do within the stored procedure to produce results in a fashion that Java will accept?
I encountered this java.sql.SQLException. In my case I was running a query in this way:
String query =
"-- a classical comment " +
"select * " +
"from MYTABLE ";
ResultSet rs = conMain.createStatement().executeQuery(query);
while(rs.next()) {
//do something...
}
rs.next() throws the exception. The reason is that, due to the comments, query results to be:
"-- a classical comment select * from MYTABLE "
hence it's all commented... query is invalid! Many examples could be shown with this mistake (with the comment in the middle of the query etc.).
Solutions: add a \n at the end of each line of the query or use comments in the /*...*/ form.
I selected an older version of the driver an it worked for me.
http://dev.mysql.com/downloads/mirror.php?id=13598 (mysql-connector-java-5.0.8.zip)

Categories

Resources