I am working on neo4j database .
And I am using this :
query="match(n:learner) where "+endTime+"<=n.registrationtime<="+startTime+" "+ " return count(n) as total,collect(n.name) as name,"
to retrieve the data on a specific counter but collect function returns data in array form . When I am taking this in String variable it returns value like this
["c154ab40-1aaf-11e7-92ae-000c298f510d",
"3044c8f0-1ab0-11e7-92ae-000c298f510d"]
I want this data in Array list so how can I convert this in arraylist.
I am using this code
try {
query="match(n:learner) where "+endTime+"<=n.registrationtime<="+startTime+" "
+ " return count(n) as total,collect(n.name) as name";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query.toLowerCase());
if(rs.next()){
int total = rs.getInt("total");
System.out.println("total="+total);
ArrayList<String> userids=new ArrayList<String>();
String name=rs.getString("name");
System.out.println("id="+name);
String[] userArray=name.split(",");
for(String user:userArray){
userids.add(user);
System.out.println("userids="+userids);
}
dataFatch.setTotal(total);
and from this code i m getting this result
id=["c154ab40-1aaf-11e7-92ae-000c298f510d","3044c8f0-1ab0-11e7-92ae-000c298f510d"]
userids=[["c154ab40-1aaf-11e7-92ae-000c298f510d"]
userids=[["c154ab40-1aaf-11e7-92ae-000c298f510d",
"3044c8f0-1ab0-11e7-92ae-000c298f510d"]]
for(String user:userArray){
userids.add(user);
}
System.out.println("userids="+userids);
userids is an ArrayList. You just need to print it out of the loop, otherwise userids is printed at any iteration
to print them run this code afterwards:
for (String userid : userids){
System.out.println("userid="+userid);
}
Related
I have a list of objects List , being the result of a HQL Query. The Objects of the list contain the data I need. I am doing the following if I know the types of the data :
(Here I know that the query was Select country, globalAmount, average from table)
for (Object record : result) {
Object[] fields = (Object[]) record;
String country = (String) fields[0];
long globalAmount = (Long) fields[1];
double average = (Double) fields[2];
System.out.println("Country "+country );
System.out.println("Global Amount "+globalAmount);
}
The problem is that sometimes, I don't know if I'll be having "Country" or "average" in the Object, and the query can be completely different :
Select average, date, message from table
Then, to retreive data, I have to do the following :
for (Object record : result) {
Object[] fields = (Object[]) record;
double average = (Double) fields[0];
Timestamp date= (Timestamp) fields[1];
String message = (String) fields[2];
System.out.println("date " +date);
System.out.println("Message "+Message);
System.out.println("Average " + Average);
}
Is there any way that I can dynamically retreive data from this List without having Cast problems?
Thank you for your help!
This is just a proto-type. What I did here is got all the column names and then based on the column name I'm type casting it to the required type.
This is just a small trick.
String query = "Select x, y, z from tablename";
//get the columns here
String colums = query.substring(7, query.indexOf("from") - 1).trim();
String []arrColums = colums.split(",");
for(int i = 0; i < arrColums.length; i++)
{
switch(arrColums[i])
{
case "X" : X x = (X)result.get(i);
case "Y" : Y y = (Y)result.get(i);
}
}
It does not to seem possible. I had to use If blocks to figure out which type I am receiving. Quite long but did not have any other option. The solution provided by Uma Kanth is smart but was not suitable for me though.
I store resultset values in the list in following way-
while(rs.next())
{
Comp_Mps_sext ref_drop=new Comp_Mps_sext();
ref_drop.setLogtime(rs.getString(1));
ref_drop.setBeam_current(rs.getString(2));
ref_drop.setBeam_energy(rs.getString(3));
ref_drop.setP44_readback(rs.getString(4));
ref_drop.setP44_setvalue(rs.getString(5));
ref_drop.setP44_vmeset(rs.getString(6));
ref_jsp.add(ref_drop);
}
where Comp_Mps_sext is the Class name.What is the ebst way to trim the values in following format ##.## and then add into the arraylsit.
EDIT-1
ref_jsp is defined as-
List<Comp_Mps_sext> ref_jsp=new ArrayList<Comp_Mps_sext>();
If you just want Strings, then a simple routine to format the result is:
private String hundreths(String in) {
int dotAt = in.indexOf(".");
if (dotAt < 0) // no decimal point??
return in + ".00";
if (dotAt + 2 < in.length())
in += "00";
return in.substring(0, dotAt + 2);
}
Then go thru your results:
ArrayList<String> myArrayList() = new ArrayList<String>();
while(rs.next())
{
Comp_Mps_sext ref_drop=new Comp_Mps_sext();
String result = rs.getString(1)
ref_drop.setLogtime(result);
myArrayList.add(hundreths(result));
....
Note that this will truncate to two places, not round the value.
I have an SQL query that bring up a string, I add that string into a list, and want to compare the result of that list, so that i can check the duplicates in said list
String q = "SELECT SURROGATE,sibling_surrogate,WINS_SEQUENCE_NUMBER FROM ppoltran";
List<List> resultSet = sqlCore.sqlExecuteQuery(q);
System.out.println("There are " + resultSet.size() + " transactions to be corrected.");
for (List list : resultSet) {
System.out.println(list.toString());
}
This is the result I get from the print
[[SURROGATE] = [547476849], [sibling_surrogate] = [1038309665], [WINS_SEQUENCE_NUMBER] = [4]]
[[SURROGATE] = [1038282064], [sibling_surrogate] = [1038282065], [WINS_SEQUENCE_NUMBER] = [0]]
[[SURROGATE] = [547476849], [sibling_surrogate] = [1038284155], [WINS_SEQUENCE_NUMBER] = [0]]
[[SURROGATE] = [1038273562], [sibling_surrogate] = [1038286005], [WINS_SEQUENCE_NUMBER] = [1]]
What I want to do is to compare from the same Surrogate, when the WINS_SEQUENCE_NUMBER repeats and save the sibling_surrogate of that results. So i want to detect the Item that have the same Surrogatesame WINS_SEQUENCE_NUMBER
I am having a lot of trouble iterating through all my records. Perhaps, by reading my code someone could help.
private String saveData(Handle handle, String username, String name, String prof, String table) {
String sqlCommand;
Map<String, Object> userResults;
for (Integer tableNum = 1; tableNum < 5; tableNum++) {
//query all tables
sqlCommand = String.format("SELECT varname FROM s" + tableNum.toString());
userResults = handle.createQuery(sqlCommand)
.bind("username", username)
.first();
//attempt to ierate all records
for (Map.Entry<String, Object> entry : userResults.entrySet()) {
Object obj = entry.getValue(); // doesnt have .get(string) as below
}
//get the desired field
logger.debug("Results: " + userResults.toString());
String varname = (String) userResults.get("varname");
if ((varname.toLowerCase()).matches(name.toLowerCase()))
return "";
}
//save data
return name;
}
How do I iterate through each record of the table?
You say this works for row1. You cannot go to the next row as there is .first(); in your handle and you have not tried to fetch next record. Modify your query - the documentation here says you can use .list(maxRows);
I am connecting to an Oracle database and querying multiple tables. My current code creates the connection and calls a PL/SQL function which contains the query. Once I have the result set, I add it to a Vector (as I am unsure the number of records each query will result in).
My problem is that I am unsure how to write a delimited file from the Vector. I imagine once I have added my result set to it, it is simply one gigantic string. I need to be able to receive each field from the query and delimit between them, as well as keep rows separate.
Here is my code:
public static void main(String[] args) throws SQLException {
// instantiate db connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (Exception e) {
throw new SQLException("Oracle JDBC is not available", e);
}
// define connection string and parameters
String url = "jdbc:oracle:thin:#//host:port/sid";
Connection conn = DriverManager.getConnection(url, "USERNAME","PASSWORD");
CallableStatement stmt = conn.prepareCall("{? = CALL <functionname>(?)}");
// get result set and add to a Vector
ResultSet rs = stmt.executeQuery();
Vector<String> results = new Vector();
while ( rs.next() ){
results.add(rs.getString(1));
}
// close result set, sql statement, and connection
rs.close();
stmt.close();
conn.close();
// write Vector to output file,
// where the file name format is MMddyyyy.txt
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
String dateStr = sdf.format(cal.getTime());
FileWriter fwrite = new FileWriter(dateStr + ".txt");
BufferedWriter out = new BufferedWriter(fwrite);
for(int i = 0; i < results.size(); i++)
{
String temp = results.elementAt(i);
out.write(temp);
}
out.close();
}catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
I am just unsure how to go about getting the information from the db and writing it to a delimited file. Thanks in advance!
If you are unsure about the number of fields in each of your rows, then probably, it won't be possible. Because to fetch all the field values from database, you need to know what is the type of each fields, and the number of fields.
But, I'll post an example for when you have fixed number of fields, that you know.
Suppose you have 4 columns per row. Now to display it in tabular form, you would have to use List of List.
If you are using Vector, use Vector of List.
Here's an example for List of List: -
List<List<String>> results = new ArrayList<List<String>>();
while ( rs.next() ) {
List<String> tempList = new ArrayList<String>();
tempList.add(rs.getString(1));
tempList.add(rs.getString(2));
tempList.add(rs.getString(3));
tempList.add(rs.getString(4));
results.add(tempList);
}
Then to print it, use this loop: -
for (List<String> innerList: results) {
for (String fields: innerList) {
System.out.print(fields + "\t");
}
System.out.println();
}
You can write it in the same form to your BufferedWriter.
Use results.toString() and truncate the braces([]) from resulting string to write all values as comma separated at once in the file.
//toString() returns comma separated string values enclosed in []
String resultString = results.toString();
//truncate leading '[' and termincating ']'
resultString = resultString.substring(1, resultString.length()-1);
//if comma is not your delimiter then use String.replaceAll()
//to replace `,` with your delimiter
//write comma separated elements all at once
out.write(resultString);
So here if you have added str1, str2 in the results Vector, then resultString with have value as str1, str2, which you may write at once using your BufferedWriter out.
Also please use Generics in both the sides of initialization as:
Vector<String> results = new Vector<String>();