How do I display arrayList contents from resultset in Java JDBC? - jdbc

So I am making a simple java project to play around with JDBC in glassfish and see how it works. The program just shows you a list of surveys and a list of questions for the survey you select. However i cant seem to display the list of questions for the survey I selected. I keep getting empty values. These are the methods I have created:
convert the resultset to object model data values
public JHAKSurvey findSurvey(long id) {
System.out.println("JDBC: FIND SURVEY");
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
JHAKSurvey survey = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.SURVEY WHERE ID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
survey = createSurveyFromResultSet(rs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
return survey;
}
private method to query the list of questions from the QUESTION table for a survey id
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ps.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}
private method to convert the find the resultset list to an question object and add it to the survey object
private void createQuestionFromResultSet(ResultSet rs, JHAKSurvey survey){
ArrayList<JHAKQuestion> qList = new ArrayList<JHAKQuestion>();
JHAKQuestion question = new JHAKQuestion();
JHAKSurvey ss = new JHAKSurvey();
//qList.add(survey.getQuestions());
try {
while (rs.next()) {
//question.setDescription(qList.toString());
question.setId(rs.getLong("ID"));
question.setDescription(rs.getString("DESCRIPTION"));
qList.add(question);
survey.setQuestions(qList);
}
System.out.println("createQuestionFromResultSet : JDBC : successful");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("createQuestionFromResultSet : JDBC : fail");
e.printStackTrace();
}
}
private method to convert a resultset to an survey object.
private JHAKSurvey createSurveyFromResultSet(ResultSet rs){
JHAKSurvey survey = new JHAKSurvey();
Boolean active = false;
String yes;
try {
yes = rs.getString("ACTIVE");
survey.setId(rs.getLong("ID"));
survey.setTitle(rs.getString("TITLE"));
if (yes.equals(Character.toString('Y'))) {
survey.setActive(true);
} else {
survey.setActive(false);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return survey;
}
What am I missing? I also seem to get error:
cannot convert from void to JHAKQuestion
When I try the method: createQuestionFromResultSet();
Thank You

Look at your method:
private void findQuestionsBySurvey(JHAKSurvey survey){
You want to get the questions of a survey, but the method returns void. Make it return a List<Question>. And in the body of the method, iterate through the resultset, transform each row into a question, add the question to a List<Question>, and return this list.
Or, if the goal of the method is to add questions to the survey passed as argument, then rename the method to
private void addQuestionsToSurvey(JHAKSurvey survey) {
and, inside the method body, call the method createQuestionFromResultSet (which should be named createQuestionsFromResultSetAndAddThemToSurvey), with the resultset and the survey as argument:
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ResultSet rs = ps.executeQuery(query);
createQuestionFromResultSet(survey);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}

Related

call an oracle function with array as parameter via hibernate

So i hava an oracle functiion like: function unbind (ids in id_table). It takes an array of ids to perform some updates on my database.
The question is how can I run my function in order to perform update operations?
What I've alreade tried:
1. Query query = getSession().createSQLQuery("call UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
but I got ora-06576 not a valid function or procedure name
Query query = getSession().createSQLQuery("execute UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
finish with ora-00900 invalid sql statement
Long [] myArray = movedIds.toArray(new Long[movedIds.size()]);
Boolean result = getSession().doReturningWork(new ReturningWork<Boolean>() {
#Override
public Boolean execute(Connection connection) throws SQLException {
CallableStatement callableStatement = connection.prepareCall("{ ? = call UNBIND(:ids)");
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.setArray(2, connection.createArrayOf("id_table", myArray));
callableStatement.execute();
return !(callableStatement.getInt(1) == 0);
}
});
finishes with java.sql.sqlfeaturenotsupportedexception unsupported feature
The app conects to the database via jboss, so I suppose that could be the problem in p. 3?
SELECT
UNBIND( id_table (6271789) ) FROM DUAL
does not work because my function performs updates...
Anyway is there any other method to run a function that takes an array as a parameter directly from java code?
here is a simple example, does this help?
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#//localhost/orcl","scott","tiger");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "{ ? = call test_func(?) }";
CallableStatement cs = null;
try {
cs = conn.prepareCall(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int inVal = 0;
cs.setInt(2, inVal);
cs.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER);
cs.executeUpdate();
int res = cs.getInt(1);
System.out.println("result is " + res);
}
}

how to convert blob data into byte array and get image from DB and send it to UI through rest api

#Override
public byte[] findByusernameAndtenantId(String username,int tenantId) throws SQLException {
Connection con=null;
Blob img ;
byte[] imgData = null ;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con=DriverManager.getConnection("jdbc:cassandra://169.46.155.77:9042/demo");
String query = "SELECT PHOTO FROM demo.IGNITE_USERS where USER_NAME=? and TENANT_ID=?";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next ())
{
img = result.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
result.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try{
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
return imgData ;
}
this is my implementation code .
#RequestMapping(value ="/Image",method = RequestMethod.POST, produces="image/jpg")
public ResponseEntity<byte[]> getImage(#RequestParam String username,#RequestParam int tenantId) throws SQLException
{
byte[] img=null;
img=authService.findByusernameAndtenantId(username,tenantId);
System.out.println("testing functionality");
return new ResponseEntity<byte[]>(img, HttpStatus.OK);
}
this is my controller code
when I run the spring boot program , and do a POST call in Postman client to get the image I am getting Class not found exception : org.apache.cassandra.cql.jdbc.Cassandra Driver.
Can you please help me how to return that image from cassandra DB stored as Blob ?

ResultSet next() is returning only one row

I am having this method
public List<Course> getCourses() throws InvalidCourseDataException {
ArrayList<Course> allCoursesFromDB = new ArrayList<>();
Connection dbConnection = null;
String getFromTableSQL = "SELECT * FROM courses";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
resultSet = statement.executeQuery(getFromTableSQL);
while (resultSet.next()) {
String courseCategory = resultSet.getString("course_category");
String courseTitle = resultSet.getString("course_title");
int courseId = resultSet.getInt("course_id");
Date startDate = resultSet.getTimestamp("starting_date");
Date endDate = resultSet.getDate("ending_date");
String description = resultSet.getString("description");
int teacherId = resultSet.getInt("teacher_id");
Course course = new Course(courseCategory, courseTitle, startDate, endDate);
course.setCourseId(courseId);
course.setTeacherId(teacherId);
course.setDescription(description);
addParticipantsIdToCourse(course);
allCoursesFromDB.add(course);
}
The getDBConnection() method is
private static Connection getDBConnection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
My problem is that resultSet.next() is returning only the first row from DB. I'am sure that I have multiple rows. I saw JDBC ResultSet is giving only one row although there are many rows in table? that question but it really doesn't answer my :)
I am sorry for the question. I found my mistake. ResultSet next() method is working fine, but I've changed its value in my addParticipantsIdToCourse(course) method :)

I get a nullpointerexception when connecting to oracle DataBase

Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.

Code Logic of when close the statement java

Well always teach me this way of open and close connections from database, then i search more and more because this is very important for the performance of my application.
Here is my Class connection
public class Connection {
jdbc:oracle:thin:#//xxx.xx.x.xxx:xxxx/xxxxx.xxxxxx.xxxxx.xxx;
protected static Connection cn = null;
protected Connection getCn() {
return cn;
}
public static void setCn(Connection cn) {
Connection.cn = cn;
}
public ResultSet select(String sql) throws Exception {
ResultSet rs = null;
Statement st = null;
try {
st = this.getCn().createStatement();
rs = st.executeQuery(sql);
} catch (java.sql.SQLException e) {
throw e;
}
return rs;
}
public void insert(String sql) throws Exception {
Statement st = null;
try {
st = this.getCn().createStatement();
st.executeUpdate(sql);
} catch (java.sql.SQLException e) {
throw e;
}
}
public Connection connect() throws Exception {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
setCn(DriverManager.getConnection(DBURL, "user", "password"));
} catch (java.sql.SQLException e) {
throw e;
}
return cn;
}
Well that was for my Connection Class, now here i have some others class that extends from my Connection class to bring me data from the DataBase.
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}
im using jsf and oracle, i think this snippet should be in my class Connection after the catch but generates me and error of the resulset is closed when i execute the method rs.next() and is logic because the statement must be close after the reading data of the resultSet, so how can i close the statement in my class Connection or in other place??? any suggestions? please help me
finally {
if (st != null) {
st.close();
}
}
A quick fix to the problem is:
finally {
try{ st.close(); }catch( Exception ex ) { /* do nothing*/ }
}
this prevents from throwing an error when something goes wrong with the statement in other places of the code ( st is null, st is closed etc.).
A more elegant solution might be creating a helper class with methods that close statements, resultsets etc. and hide exceptions that occur:
class DbCloser{
static void closeQuietly( Statement st ){
try{
st.close();
} catch( Exception ex ){
/* do nothing */
}
}
static void closeQuietly( ResultSet rs ){
try{
rs.close();
} catch( Exception ex ){
/* do nothing */
}
}
// .... etc.
}
and then use that helper class in finally blocks in code:
finally {
DbCloser.closeQuietly( st );
}
There is ready-made DbUtils package from Appache Commons that has already implemented such helper methods, just download this library and place it in the class-path, see this links for details:
http://commons.apache.org/proper/commons-dbutils/
http://commons.apache.org/proper/commons-dbutils/apidocs/index.html
And finally I would suggest to place close methods only in finnaly blocks:
try {
......
rs = this.select(sql);
.......
...........
// Do not close the statement here ......
// rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
// ..... always close it here !!!
DbUtils.closeQuietly( st );
.........
}
i use this one
finally {
try{
if(st!=null){
st.close();
st=null;
}
}catch( Exception ex )
{
/* you can log this*/
}
}
Finally, I solved it like this:
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close();
rs.getStatement().close(); 'This works for me =)
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}

Resources