Here i got value for catname from parameter as movie but in database its have corresponding value as 1, same for music->2, game->3....
"WHERE (\n" +
"\t\t(`Post`.`status` = 1)\n" +
"\t\tAND (`Post`.`postto_id` =\"+catname+\" \")\n" +
"\t\t)" +
"ORDER BY `Post`.`id` desc LIMIT 5", new CrelistMapper());
} catch (Exception e) {
throw e;
}
}
private class CrelistMapper implements ResultSetExtractor<List<Creativity>> {
public List<Creativity> extractData(ResultSet resultSet) throws SQLException {
List<Creativity> crelistList = new ArrayList<Creativity>();
while (resultSet.next()) {
Creativity userObject = new Creativity(resultSet.getString("**postto_id**"),
Here i got value as movie in "postto_id" how can i convert it into 1 instead of movies from parameter?
I believe you are looking for parse int from Integer class.
import java.lang.Integer;
public class test{
public static void main(String[] args){
String stringId = "1";
int intFromString = Integer.parseInt(stringId);
System.out.println(intFromString);
}
}
Look here for a version of the overloaded method that meets your purpose
Related
I have a query that when I execute it on database, it gives me decimals, but when I execute the same query on my app, it gives me the numbers without decimals.
I have my variables setted as "double" and they are correctly "linked" to the database, I put the code below.
Here is where I call the method:
List<DatosEstadistica> listaDatosEstadistica = facade.obtenerDatosIngresos(filtro);
The facade:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro)
throws ServiceException {
return this.modeloService.obtenerDatosIngresos(filtro);
}
The service implement:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro)
throws ServiceException {
try {
return this.getDao().obtenerDatosIngresos(filtro);
} catch (HibernateException he) {
throw new ServiceException(he);
}
}
And the query instructions:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro) {
try {
StringBuffer query = new StringBuffer();
query.append("sum( decode ( a.indingdev,'R',0, "
+ "nvl(a.impingdev,0) + "
+ "nvl(a.imprecargo_ing,0) "
+ ") "
+ ") as total_recaudado, "
+ "from tableM m, table_f f, table_a a "
+ "where m.reg = f.reg");
SQLQuery querySQL = getHibernateTemplate().getSessionFactory().getCurrentSession()
.createSQLQuery(query.toString());
querySQL.setResultTransformer(Transformers.aliasToBean(DatosEstadistica.class));
return querySQL.list();
} catch (HibernateException qe) {
throw qe;
}
}
And datosEstadistica.class:
public class DatosEstadistica implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 88592689034562323954L;
private double TOTAL_RECAUDADO;
/**
* Instantiates a new datos estadistica.
*/
public DatosEstadistica() {
}
public double getTOTAL_RECAUDADO() {
return TOTAL_RECAUDADO;
}
public void setTOTAL_RECAUDADO(double tOTAL_RECAUDADO) {
TOTAL_RECAUDADO = tOTAL_RECAUDADO;
}
}
But I don't know why it doesn't give me decimals as in the same query executed on the database. Anyone can helps me, please?
EDIT:
Here is where I printed out the results, but it doesn't print the decimals, because the query List "listDatosEstadistica" return numbers without decimals:
celdaDatos.setCellValue((listaDatosEstadistica.get(i).getTOTAL_RECAUDADO()));
The current question is the second part of this ODCI related question.
I have implemented a collection type in Oracle SQL which is practically defined as a type and a table of that type.
CREATE TYPE row_type AS OBJECT
(
C1 VARCHAR2(50),
C2 VARCHAR2(50),
C3 VARCHAR2(50)
);
/
CREATE TYPE row_type_set AS TABLE OF row_type;
Also, I have defined an ODCI type with its implementation as a Java Stored Procedure within database:
SQL:
CREATE OR REPLACE TYPE ODCIImpl AS OBJECT (
key INTEGER,
STATIC FUNCTION ODCITableStart(sctx OUT ODCIImpl, cur SYS_REFCURSOR)
RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableStart(oracle.sql.STRUCT[], java.sql.ResultSet) return java.math.BigDecimal',
MEMBER FUNCTION ODCITableFetch(self IN OUT ODCIImpl, nrows IN NUMBER,
outSet OUT row_type_set) RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableFetch(java.math.BigDecimal, oracle.sql.ARRAY[]) return java.math.BigDecimal',
MEMBER FUNCTION ODCITableClose(self IN ODCIImpl) RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableClose() return java.math.BigDecimal'
);
/
Java Stored Procedure:
import java.io.*;
import java.util.*;
import oracle.sql.*;
import java.sql.*;
import java.math.BigDecimal;
import oracle.CartridgeServices.*;
// stored context type
public class StoredCtx
{
ResultSet rset;
public StoredCtx(ResultSet rs) { rset=rs; }
}
// implementation type
public class ODCIImpl implements SQLData
{
private BigDecimal key;
final static BigDecimal SUCCESS = new BigDecimal(0);
final static BigDecimal ERROR = new BigDecimal(1);
final static int MAX_COLUMNS = 3;
// Implement SQLData interface.
String sql_type;
public String getSQLTypeName() throws SQLException
{
return sql_type;
}
public void readSQL(SQLInput stream, String typeName) throws SQLException
{
sql_type = typeName;
key = stream.readBigDecimal();
}
public void writeSQL(SQLOutput stream) throws SQLException
{
stream.writeBigDecimal(key);
}
// type methods implementing ODCITable interface
static public BigDecimal ODCITableStart(STRUCT[] sctx,ResultSet rset)
throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
// create a stored context and store the result set in it
StoredCtx ctx=new StoredCtx(rset);
// register stored context with cartridge services
int key;
try {
key = ContextManager.setContext(ctx);
} catch (CountException ce) {
return ERROR;
}
// create a ODCIImpl instance and store the key in it
Object[] impAttr = new Object[1];
impAttr[0] = new BigDecimal(key);
StructDescriptor sd = new StructDescriptor("ODCIIMPL",conn);
sctx[0] = new STRUCT(sd,conn,impAttr);
return SUCCESS;
}
public BigDecimal ODCITableFetch(BigDecimal nrows, ARRAY[] outSet)
throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
// retrieve stored context using the key
StoredCtx ctx;
try {
ctx=(StoredCtx)ContextManager.getContext(key.intValue());
} catch (InvalidKeyException ik ) {
return ERROR;
}
// get the nrows parameter, but return up to 10 rows
int nrowsval = nrows.intValue();
// create a vector for the fetched rows
Vector v = new Vector(nrowsval);
int i=0;
StructDescriptor outDesc =
StructDescriptor.createDescriptor("ROW_TYPE", conn);
Object[] out_attr = new Object[MAX_COLUMNS];
ResultSetMetaData rsmd = ctx.rset.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while(nrowsval>0 && ctx.rset.next()){
for(int j = 0; j < columnsNumber; j++) {
if(j == MAX_COLUMNS)
break;
out_attr[j] = (Object)ctx.rset.getString(j+1);
}
v.add((Object)new STRUCT(outDesc, conn, out_attr));
i+=1;
nrowsval-=1;
}
// return if no rows found
if(i==0) return SUCCESS;
// create the output ARRAY using the vector
Object out_arr[] = v.toArray();
ArrayDescriptor ad = new ArrayDescriptor("ROW_TYPE_SET",conn);
outSet[0] = new ARRAY(ad,conn,out_arr);
return SUCCESS;
}
public BigDecimal ODCITableClose() throws SQLException {
// retrieve stored context using the key, and remove from ContextManager
StoredCtx ctx;
try {
ctx=(StoredCtx)ContextManager.clearContext(key.intValue());
} catch (InvalidKeyException ik ) {
return ERROR;
}
// close the result set
Statement stmt = ctx.rset.getStatement();
ctx.rset.close();
if(stmt!=null) stmt.close();
return SUCCESS;
}
}
After all of this, I've implemented a pipelined function that can be called using a cursor.
CREATE OR REPLACE FUNCTION Exec_Remote_SQL_JSP(p SYS_REFCURSOR) RETURN row_type_set
PIPELINED USING ODCIImpl;
/
My question now is how can we implement an ODCITableDescribe method in a Java Stored Procedure in order to output any data type in the emulated table? First of all, is it possible at all? I didn't seem to find any relevant information about this on the Oracle documentation from here and here
If it is possible to do so, it is self-explainable that we do not need anymore the collection types mentioned at the beginning. The emulated table should have the same size and data types as the table from which we intend to select information.
I am trying to write a Spring Boot Controller that allows the user to make arbitrary SELECT queries to a Postgres database and see the result. I implemented this by using a form like the one in the link. The project is based on this starter app.
Code:
#Controller
#SpringBootApplication
public class Main {
#Value("${spring.datasource.url}")
private String dbUrl;
#Autowired
private DataSource dataSource;
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
#GetMapping("/query")
public String queryForm(Model model) {
model.addAttribute("query", new Query());
return "query";
}
#PostMapping("/query")
public String querySubmit(#ModelAttribute Query query) {
try (final Connection connection = dataSource.getConnection()) {
final Statement stmt = connection.createStatement();
final String rawQueryContent = query.getContent().trim();
final String queryContent;
if(!rawQueryContent.toLowerCase().contains("limit")) {
queryContent = rawQueryContent + " LIMIT 500";
} else {
queryContent = rawQueryContent;
}
final ResultSet rs = stmt.executeQuery(queryContent);
final StringBuilder sb = new StringBuilder();
while (rs.next()) {
sb.append("Row #" + rs.getRow() + ": " + rs.toString() + "\n");
}
query.setContent(sb.toString());
rs.close();
stmt.closeOnCompletion();
} catch (Exception e) {
query.setContent(e.getMessage());
}
return "queryresult";
}
#Bean
public DataSource dataSource() throws SQLException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
}
}
}
The form looks like this:
But the output I am getting looks like this:
Row 1: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 2: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 3: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 4: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
This is not what I want! I want to see the actual rows in the database, as in:
Row 1: "Dave" | 23 | "Philadelphia"
Row 2: "Anne" | 72 | "New York"
Row 3: "Susie" | 44 | "San Francisco"
Row 4: "Alex" | 22 | "Miami"
Heck, I would rather get the raw string output that I normally get when I hand-type SQL into the database than the address in memory of the ResultSet.
How do I get the actual database output without knowing in advance exactly how many columns there will be in the table or the types of the columns?
I would suggest, for starters to simplify your code by using the JdbcTemplate combined with a ResultSetExtractor to simplify the code. You can use the ResultSet itself to get the number of columns for a result.
I'm also not sure why you are redefining the DataSource.
All in all something like the code below should do the trick (haven't tested it and typed it from the top of my head, so might need some polishing).
#Controller
#SpringBootApplication
public class Main {
#Autowired
private JdbcTemplate jdbc;
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
#GetMapping("/query")
public String queryForm(Model model) {
model.addAttribute("query", new Query());
return "query";
}
#PostMapping("/query")
public String querySubmit(#ModelAttribute Query query) {
final String rawQueryContent = query.getContent().trim();
final String queryContent;
if(!rawQueryContent.toLowerCase().contains("limit")) {
queryContent = rawQueryContent + " LIMIT 500";
} else {
queryContent = rawQueryContent;
}
String content = jdbc.query(queryContent, new ResultSetExtractor<StringBuilder>() {
public StringBuilder extractData(ResultSet rs) {
StringBuilder sb = new StringBuilder();
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
int row = rs.getRow();
sb.append(rs.getRow()).append('|');
for (int i = 1 ; i <= columns ; i++) {
sb.append(rs.getObject(i)).append('|');
}
}
return sb.toString();
}
});
query.setContent(content);
return "queryresult";
}
}
See also How to get the number of columns from a JDBC ResultSet? on how to get the number of columns.
I should make separate class with reading library of books, updating etc.
Class books should have:
parametric constructor plus override for toString()
Method getAll static to read all data for DB
Method getById is reading data when we give ID, also static.
but i did next:
Main.java
try {
ArrayList<String[]> allBooks = Books.getAll("SELECT * FROM books");
for (String[] izd : allBooks) {
System.out.println("Books id: " + izd[0] + " Date of publishing: " + izd[1] + " Id of books: " + izd[2]+...);
}
} catch (Exception e) {
System.out.println(e);
}
Books.java
static ArrayList<String[]> getAll(String stt) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException
{
connect();
Statement stmt = conn.createStatement();
stmt.executeQuery(stt);
ResultSet rs = stmt.getResultSet();
int columnsNum = rs.getMetaData().getColumnCount();
ArrayList<String[]> result = new ArrayList<String[]>();
while(rs.next())
{
String[] rowArr = new String[columnsNum];
for(int i=0;i<columnsNum;i++)
rowArr[i]=rs.getString(i+1).toString();
result.add(rowArr);
}
close();
return result;
}
I really don't understand how.. Any help will be like :D
You are not really giving much information about your goal here, so I can only guess. I would expect something like this:
public class Book {
private String title;
//...
//constructor
public Book(String theTitle) {
this.title = theTitle;
}
public static ArrayList<Book> getAll(String stt) { /* ... */ }
public static Book getById(int id) { /* ... */ }
}
And in your getAll function you probably want something like this:
while(rs.next())
{
Book aBook = new Book(rs.getString("title"));
result.add(aBook);
}
I have written a code to sort name by id and firstname.
import java.io.*;
import java.util.*;
public class TestEmployeeSort {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option=null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
option=br.readLine();
int a=Integer.parseInt(option);
switch(a)
{
case 1:
Collections.sort(coll);
printList(coll);
break;
case 2:
Collections.sort(coll,new EmpSortByFirstName());// sort method
printList(coll);
break;
case 3:
Collections.sort(coll,new SortByLastName());// sort method
printList(coll);
}
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i=0;i<list.size();i++) {
Employee e=list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() +"\t" + e.getDate_Of_Joining()+"\t"+e.getDate_Of_Birth());
}
}
}
for sorting by id and first name i have this code in the Sort_this class
public class EmpSortByFirstName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getFirstName().compareTo(o2.getFirstName()); }}
similarly for id.
Now i want to change my program like i have to get input from uset on which basis you want to sort. If the user gives id, I have to sort by id. If the user gives firstname then sort by first name. I want to use if statement. If user enters 1 it has to sort by id 2 it has to sort by first name
Create a map of user input tokens (string, integer, etc.) to Comparator<Employee>, and just use the appropriate one.
Did you mean you want to get rid of using switch? If so, you can try having a map of registered soter:
import java.io.*;
import java.util.*;
public class TestEmployeeSort {
private static class EmployeeSortingManager {
private final List list;
private final Map<Integer, Comparator> registeredSorter = new HashMap<Integer, Comparator>();
public EmployeeSortingManager(List list) {
this.list = list;
registerAvailableSorters();
}
private void registerAvailableSorters() {
registeredSorter.put(1, null);
registeredSorter.put(2, new EmpSortByFirstName());
registeredSorter.put(3, new SortByLastName());
}
public void sortBy(int i) {
Comparator comparator = registeredSorter.get(i);
if (registeredSorter.get(i) != null) {
Collections.sort(list, comparator);
} else {
Collections.sort(list);
}
}
}
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option = null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
option = br.readLine();
int a = Integer.parseInt(option);
employeeSortingManager.sortBy(a);
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i = 0; i < list.size(); i++) {
Employee e = list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
}
}
}
Another attemp to remove implementation of Every single comparator through the use of reflection. This is mmore complicated and may introduced more error if you are working with values which are not Comparable, e.g. String, Integer, Double. You will have to be careful.
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class TestEmployeeSort {
private static class EmployeeSortingManager {
private final List list;
private final Map<Integer, Method> registeredSorter = new HashMap();
private BasicComparator comparator = new BasicComparator();
public EmployeeSortingManager(List list) {
this.list = list;
registerAvailableSorters();
}
private void registerAvailableSorters() {
registeredSorter.put(1, null);
registeredSorter.put(2, getEmployeeGetMethod("firstName"));
registeredSorter.put(3, getEmployeeGetMethod("lastName"));
}
private Method getEmployeeGetMethod(String fieldName) {
Method method = null;
try {
// create java style get method name from field name, e.g. getFieldName from fieldName
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
method = Employee.class.getMethod(getMethodName);
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
}
// null is return if you give invalid field name
return method;
}
public void sortBy(int i) {
Method get = registeredSorter.get(i);
if (get != null) {
comparator.setGetMethod(get);
Collections.sort(list, comparator);
} else {
Collections.sort(list);
}
}
}
private static class BasicComparator implements Comparator<Employee> {
private Method aGetMethod = null;
public void setGetMethod(Method aGetMethod) {
this.aGetMethod = aGetMethod;
}
#Override
public int compare(Employee o1, Employee o2) {
try {
Object value1 = aGetMethod.invoke(o1);
Object value2 = aGetMethod.invoke(o2);
if (value1 instanceof Comparable && value2 instanceof Comparable) {
// this should work with String, Integer, Double, etc. They all implement Comparable interface.
return ((Comparable) value1).compareTo((Comparable) value2);
} else {
// you will need to add your own comparision for other type of variable;
// obviously it is not possible to have a single comparison
// if your get method return something else.
}
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
}
// if cannot compare then they are equal.
return 0;
}
}
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option = null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
option = br.readLine();
int a = Integer.parseInt(option);
employeeSortingManager.sortBy(a);
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i = 0; i < list.size(); i++) {
Employee e = list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
}
}
}