Converting an ActiveRecord:Relation to java array - java

I am running a 'where' query which is running on a table MyTable in my rails application.
I want to convert the results of a specific column from this query(ActiveRecord::Relation) to Java Array of String type.
This is what I am doing :
employeesJavaArray=MyTable.where("salary = ?",100).pluck(:columnName).to_java(java.lang.String)
However I am receiving this error in my logs :-
TypeError (could not coerce Fixnum to class java.lang.String):
Can you please help me out what could be wrong with the statement that I have written.

I would ensure that the array only includes string (by calling to_s) first:
employeesJavaArray = MyTable.where("salary = ?",100)
.pluck(:columnName)
.map(&:to_s)
.to_java(java.lang.String)

Related

DATEDIFF not working in JAVA

Am running a query from JAVA , the query contains DATEDIFF function in which the parameter is a keyword,we can give yy,mm,day,etc.. so am getting these keyword from user as parameter and setting it in query, but the issue is it wont execute, it gives an exception as Invalid parameter for argument 1. If i run the same query in CLIENT it gives result, but if i give quotes to keyword like 'day' it gives the same error in CLIENT also. So my question how will I set it in the query from JAVA. Currently am doing like
for (String param : params) {
try {
namedParameterStatement.setObject(param,requiredFilterValues.get(param));
} catch (RuntimeException e) {
}
}
This is the query am using
SELECT CUST_KEY,Eff_Date_From,Eff_Date_To, DATEDIFF(:intervals,Eff_Date_From,Eff_Date_To) as datediffs,Active FROM CUSTOMER_DIM WHERE Active = :active
Am passing values for params intervalsand active, The issue is with :intervals as it takes keywords.
I think the java program setting the parameter as string that is why its generating error.. How can i implement this?
The problem is that you can only pass values using parametrized queries. You can't pass keywords (nor object names). In the case of your query. they would be passed as the equivalent of DATEDIFF('<your-keyword>', .., which wouldn't work either.
There is no solution except manually concatenating the required keyword into the query, or creating a convoluted query using a CASE-construct to get the right value depending on the value passed:
case ? when 'MONTH' then datediffer(MONTH, ..) when .. end
You may need to explicitly cast the parameter to a VARCHAR to get it to work.

How to convert a hive string query into abstract syntax tree using Java API?

I know I can get the AST using the explain extended command. My question is, how to get the same using the Java API.
My goal is to get the following data about queries:
Database source and target (if applied).
Table source and target (if applied).
Fields involved in the query.
I know I can get them above data directly from query string using Regex, but I want to use Java API.
Do you have any other idea how to do that?
You can use Hive Parser for this. It simply takes the query and convert it into AST which is similar explain command. Here is a simple example:
ParseDriver pd = new ParseDriver();
ASTNode tree = pd.parse("Select * from table1");
System.out.println(tree.dump());
The output for this will be
nil
TOK_QUERY
TOK_FROM
TOK_TABREF
TOK_TABNAME
table1
TOK_INSERT
TOK_DESTINATION
TOK_DIR
TOK_TMP_FILE
TOK_SELECT
TOK_SELEXPR
TOK_ALLCOLREF
<EOF>

In Java, pass large double as parameter to sql server, causing "Error converting data type varchar to numeric."

I'm using Spring Jdbc to make insertion with Sql Server. But recently I have a large double with more than 10 digits (let say 11123456789.00), which becomes 1.1123456789E10 when I print it out without the formatting.
Here is how I pass it to Sql Server:
double largeDouble = 11123456789.00;
MapSqlParameterSource paraMap = new MapSqlParameterSource()
paraMap.addValue("largeDouble", largeDouble);
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(getJdbcTemplate());
simpleJdbcCall.withProcedureName("someStoredProcedure").execute(paraMap);
The data type of largeDouble field in Sql Server is decimal(19,2).
And this error shows "Error converting data type varchar to numeric." after running the program.
I'm wondering why this situation happens and how to solve it.
Try the other method with extra parameter to specify the SQL type.
paraMap.addValue("largeDouble", largeDouble, Types.LONG);
Well I manage to find the program, which is the xml parameter of a large Double. In xml, it become a number with scientific notation, violate the numeric type of the column.

What is the best way to import an XML string into a SQL Server table

I am working with a 3rd product called JPOS and it has an XMLPackager whereby I get a string from this packager that contains a record in an XML format such as:
<MACHINE><B000>STRING_VALUE</B000><B002>STRING_VALUE</B002><B003>STRING_VALUE</B003><B004>STRING_VALUE</B004><B007>STRING_VALUE</B007><B011>STRING_VALUE</B011><B012>STRING_VALUE</B012><B013>STRING_VALUE</B013><B015>STRING_VALUE</B015><B018>STRING_VALUE</B018><B028>STRING_VALUE</B028><B032>STRING_VALUE</B032><B035>STRING_VALUE</B035><B037>STRING_VALUE</B037><B039>STRING_VALUE</B039><B041>STRING_VALUE</B041><B043>STRING_VALUE</B043><B048>STRING_VALUE</B048><B049>STRING_VALUE</B049><B058>STRING_VALUE</B058><B061>STRING_VALUE</B061><B063>STRING_VALUE</B063><B127>STRING_VALUE</B127></MACHINE>
I have a SQL server table that contains a column for each of the listed. Not that it matters but I could potentially have thru defined with specific STRING_VALUEs. I'm not sure what is the best way to go about this in Java. My understanding is that SQL Server can take an XML string (not document) and do an insert. Is it best to parse each value and then put into a list that populate each value into? This is the first time I've used an XML file and therefore trying to get some help/direction.
Thanks.
Sorry, one of my colleagues was able to help and provide a quick answer. I'll try it from my Java code and it looks like it should work great. Thanks anyway.
Here is the SP that she created whereby I can pass in my XML string and bit value:
CREATE PROCEDURE [dbo].[sbssp_InsertArchivedMessages]
(
#doc varchar(max),
#fromTo bit
)
AS
BEGIN
DECLARE #idoc int, #lastId int
EXEC sp_xml_preparedocument #idoc OUTPUT, #doc
INSERT INTO [dbo].[tblArchivedMessages]
SELECT * FROM OPENXML(#idoc, '/MACHINE', 2) WITH [dbo].[tblArchivedMessages]
SET #lastId = (SELECT IDENT_CURRENT('tblArchivedMessages'))
UPDATE [dbo].[tblArchivedMessages]
SET FromToMach = #fromTo
WHERE ID = #lastId
END
GO
Regards.

How to call PostgreSQL procedure in Java?

How to make query like this in Java and get the results:
SELECT filedata.num,st_area(ST_Difference(ST_TRANSFORM(filedata.the_geom,70066),filedata_temp.the_geom))
FROM filedata, filedata_temp
Where filedata.num=filedata_temp.num
Or, I think will be better if I create procedure in Postgres from this query.
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS void AS
$$
BEGIN
SELECT filedata.num,st_area(ST_Difference(ST_TRANSFORM(filedata.the_geom,70066),filedata_temp.the_geom))
FROM filedata, filedata_temp
Where filedata.num=filedata_temp.num
end;
$$
LANGUAGE 'plpgsql'
and call it
Connection ce_proc= null;
ce_proc = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456");
java.sql.CallableStatement proc = ce_proc.prepareCall("{get_geom_difference()}");
proc.execute();
proc.close();
ce_proc.close();
But how to get results from this procedure in Java?
UPDATE
I tried this SP
DROP FUNCTION get_geom_difference();
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS integer AS
$$
DECLARE
tt integer;
BEGIN
SELECT filedata.num INTO tt
FROM filedata
Where filedata.num=1;
RETURN tt;
END;
$$
LANGUAGE 'plpgsql'
and call
Class.forName("org.postgresql.Driver");
Connection connect= null;
connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456");
java.sql.CallableStatement proc = connect.prepareCall("{?=call get_geom_difference()}");
proc.registerOutParameter(1, java.sql.Types.INTEGER);
proc.executeQuery();
ResultSet results = (ResultSet) proc.getObject(1);
and got an error:
org.apache.jasper.JasperException: An exception occurred processing
JSP page /commit_changes.jsp at line 25in lineproc.executeQuery();
root cause javax.servlet.ServletException:
org.postgresql.util.PSQLException: No results were returned by the
query
But query
SELECT filedata.num
FROM filedata
Where filedata.num=1;
returns 1.
Where is mistake?
You can largely simplify the function. (Keeping simplistic function for the sake of the question.)
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS integer AS
$BODY$
SELECT num
FROM filedata
WHERE num = 1
LIMIT 1; -- needed if there can be more than one rows with num = 1
$BODY$ LANGUAGE SQL;
Though, technically, what you have in the question would work, too - provided the data type matches. Does it? Is the column filedata.num of type integer? That's what I gather from the example. On your other question I was assumingnumeric for lack of information. At least one of them will fail.
If the return type of the function doesn't match the returned value you get an error from the PostgreSQL function. Properly configured, your PostgreSQL log would have detailed error messages in this case.
What do you see, when you create the above function in PostgreSQL and then call:
SELECT get_geom_difference(1);
from psql. (Preferably in the same session to rule out a mixup of databases, ports, servers or users.)
Calling a simple function taking one parameter and returning one scalar value seems pretty straight forward. Chapter 6.1 of the PostgreSQL JDBC manual has a full example which seems to agree perfectly with what you have in your question (My expertise is with Postgres rather than JDBC, though).
There are quite a few different CallableStatement constructors, but only two of them let you get results back.
A ResultSet is returned by CallableStatement.executeQuery(). There's a good complete example in the link above.
I don't know if getting a scalar result back from a CallableStatement is legal. I'd expect PgJDBC to translate it to a rowset of one row, though, so it should work.
Your query example is typical. So what you will need is
Java Database Connectivity (JDBC)
and everything needed to serv it, is in package java.sql
So at this point I recoemnd you to read some tutorial and if you have some particular problem write about it on SO.
You will need JDBC to do that. You should be able to find all JDBC related information here.
Take a look here for a more detailed tutorial on how to connect your Java application to your PostgreSQL.
works 100% java 7 and postgres pgadmin 2016, Use createNativeQuery In your transaction write this
and change myschema.mymethodThatReturnASelect
for the scheme and the name of your function.
#Override
public List<ViewFormulario> listarFormulario(Long idUsuario) {
List<ViewFormulario> list =null;
try {
Query q = em.createNativeQuery("SELECT * FROM myschema.mymethodThatReturnASelect(?);");
q.setParameter(1, idUsuario);
List<Object[]> listObject = (List<Object[]>) q.getResultList();
if (listObject != null && !listObject.isEmpty()) {
list = new ArrayList<>();
for (Object o[] : listObject) {
ViewFormulario c = new ViewFormulario();
c.setIdProyecto(o[0] != null ? Long.valueOf(o[0].toString()) : -1L);
...etc...etc.

Categories