insert "Finally" to complete the code [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i hav written a program in java using both get and set method....but it does not give me the desired output it tells insert finally block my code is given below..in the console of eclipse it shows only connected but no values of table displayed
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
}
}
public List<User> set_all_data() {
List<User> usersList = new ArrayList<User>();
try {
PreparedStatement stmt = connection.prepareStatement("INSERT INTO spl_user_master(name,email,mobile,password,role,status,last_update)VALUES(?,?,?,?,?,?,?)");
stmt.setString(1, "Charlie Sheen");
stmt.setString(2, "help#glomindz.com");
stmt.setString(3, "9554087107");
stmt.setString(4, "cbf91a71c21d5ec348b0c749b2f0055k");
stmt.setString(5, "user");
stmt.setString(6, "3");
stmt.setString(7, "2013-07-02 22:05:16");
boolean execute = stmt.execute();
System.out.println(execute);
stmt.getResultSet();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usersList;
}
public static void main(String[] args) {
UserServicesDAO userdao = new UserServicesDAO();
List<User> data = userdao.get_all_data();
List<User> data1 = userdao.set_all_data();
System.out.println(data);
System.out.println(data1);
System.exit(0);
}
}
whats wrong with the code plz specify

In java, try block must be followed either by a catch or a finally block. In your code you have the below try block, which is not followed by a catch/finally block(s).
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
} // missing catch/finally statements
You can either add a catch block to handle any exception happening in the above try block code or put a finally block. The general construct for a try block is
try {
code
}
catch and finally blocks . . .
Learn more about java exception handling here: http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

You can not have only try{ } in Java. try { } block must be followed by either catch{ } or finally{ }.
So here you should use either catch{ } or finnaly{ } for code utilization.
try{
....
....
}finally{
//cleanup
}
try{
....
....
}catch(Exception e)
{
....
....
}
You can also refer this :
http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

You need a catch block if you want to catch exceptions.
try {
....
} catch (Exception e) {
....
}
If you use try and finally combination, note that try is there only to allow finally.

You don't assign stmt.getResultSet(); to anything! UserList is an empty list as nothing is added to it. You need to add the results of stmt.getResultSet(); to the list.
For finally: The code block in finally will be executed for sure - but it is NOT sure when! Use finally to close database connections or other clean up work. Or better, do not use it at all. http://my.safaribooksonline.com/book/programming/java/9780137150021/creating-and-destroying-objects/ch02lev1sec7
Use a catch block to catch errors

You can not have a try block only. To have a try block you must have at least one catch block or a finally block

Related

Try with resource how to use custom logic for closing connection

In the below example we are closing connection and prepared statement using try with resource. It will close connection and prepared statement.
And also we are using 2 try block as explained below
For closing connection and prepared statement
Closing result set
In future, if we have any file-related operation then we'll need to write another try with resource block
try (Connection con = ds.getConnection();
PreparedStatement ps = con.prepareStatement(sql);) {
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
list.add(rs.getInt("id"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
But if we are not using try with resource then we can rewrite above login in single try catch block as below
try {
Connection con = ds.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getInt("id"));
}
} catch (Exception e) {
// Closing RS
// Closing PS
// Closing Connection or Customized closing connection logic
}
Question: Even if we have any custom operation while closing connection, is it possible to use a try with resource block?
Also please suggest which one better solution in that case.
Try with resources is a better solution because it uses your connections only inside the "try" block. BUT :
catch (SQLException e)
is not the same thing with :
catch (Exception e)
The (Exception e) will catch SQLException and if you said that you want to do some file related operations, will catch maybe a FileNotFoundException or IOException too so this catch is not very suggestive. In my opinion you should first read the Single Responsibility Principle and then you'll see that the best option to handle your problem is to create 2 try blocks which will handle independently the operations like this:
public static List<Integer> getAllProducts() {
List<Integer> productIds = new ArrayList<>();
try (Connection con = ds.getConnection(); PreparedStatement ps = con.prepareStatement(sql);) {
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
productIds.add(rs.getInt("id"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return productIds;
}
public static void writeSomething(String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("StackOverflow");
} catch (IOException e) {
e.printStackTrace();
}
}
I've had a similar issue a couple of weeks ago. You don't need to have multiple try-with-resources, you can only have one see this.
But in your second sample of code, you don't want to close your connection and all in the catch block. You must use the finally block.
In short you can use only one try-with-resources for the "normal" stuff, and create another try-catch-finally inside the latter (or use call to a custom method) to handle and close your customs operations.
try (Connection conn = datasource.getConnection();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(request); ) {
while (rs.next())
{
// Do your stuff.
}
try
{
// Do your stuff.
} catch (Whatever e) {
// Handle.
} finally {
// Close your custom stuff.
}
} catch (SQLException ex) {
// throw something.
}
Hope this helps.

My ResultSet is always closed when I return it from my method

I have the following class:
public class Refunds {
ResultSet dataToHash = null;
public Refunds (String UrnId) {
Database db = null;
CallableStatement callable;
String query = "select * from testmdb.dbo.ApEdiZcusSaSendFile where SourceID='LAN' and UrnID=?";
// Get database connection
try {
db = new Database("jdbc/refund");
} catch (NamingException | SQLException e1) {
e1.printStackTrace();
}
// Run the query
try {
callable = db.connection.prepareCall(query);
callable.setString(1, UrnId);
dataToHash = callable.executeQuery();
} catch (SQLException s) {
System.out.println("A SQL exception was thrown while running the query: ");
s.printStackTrace();
} catch (Exception e) {
System.out.println("A general exception was thrown while running the query: ");
e.printStackTrace();
} finally {
db.closeConnection();
}
}
public ResultSet getDataToHash() {
return dataToHash;
}
}
And I use it like this:
// Get the result set
Refunds refunds = new Refunds(urnId);
ResultSet dataToHash = refunds.getDataToHash();
However, every single time dataToHash is .closed(). I don't close my ResultSet. Whatever the problem is, how can I modify this code so that when I get it, it won't be closed?
PS - Just ignore my old school System.outs...
You close the connection, and that closes the ResultSet.
Instead of storing the ResultSet in a class member, store it in a local variable inside Refunds, and read all the data from it before returning from the Refunds method and closing the connection.

Java Class error in Eclipse

Giving error at line 12 "This method must return a result of type Boolean".
I have written my code in try catch block. If a move the resultset operation below the catch block then the error appears on resultset object.
Where am I wrong, Please answer me. Thank you.
public class LoginService {
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
return true;
} else {
System.out.println("User does not exists !!");
return false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When your code catches an exception you are simply printing the stacktrace and then allowing the function to continue.
However, after the catch blocks, you have no return statement, which is what the complaint is.
As others have mentioned, you're missing a return statement either in the catch blocks or after the catch blocks. Here's my boiler plate example of a function that returns a boolean:
bool foo()
{
bool result = false;
//do stuff, and set result to true at some point
return result;
}
This pattern is beneficial because it helps reduce the number of returns in your functions. There are some coding styles out there that won't allow more than 2 return statements in a function, for example.
Here it is applied to your function:
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
Boolean result = false;
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
result = true; //--------------------This line changed!
} else {
System.out.println("User does not exists !!");
result = false; //-------------------This line changed!
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
You should return in catch blocks too. Or in finally block.
You need to add a return statement after your catch block.
Your method may throw an exception, in this case, the code that will be executed will be in the catch clauses.
Add a finally clause after the catch's with the desired value for when this happens.
The problem is that if an exception occurs, nothing is returned. I would suggest adding
return false;
to all of your catch blocks

Why is my JDBC call failing to return anything? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I can connect the JDBC driver connect to the database. Break points show it has a connection id and the fields are properly filled, but after execution of the select statement, no rows are returned even though data is in the database and the SQL call works properly in workbench. It only returns field names without any data.
Why aren't any rows being returned?
Code:
public class DBConnect {
private static Connection conn;
public static String url = "jdbc:mysql://localhost/efwalter";
public static String user = "root";
public static String pass = "XXXXXXXXX";
private PreparedStatement prep;
public void open_Con() throws ClassNotFoundException {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
} catch (SQLException ex) {
infoBox(ex.toString(), "ERROR");
}
}
public ResultSet get_data(String SQL) {
try {
prep = conn.prepareStatement("SELECT * FROM efwalter.impact_tests");
ResultSet rs = prep.executeQuery();
return rs;
} catch (SQLException ex) {
infoBox(ex.toString(), "ERROR");
return null;
}
}
public void close_Con() {
try {
conn.close();
} catch (SQLException ex) {
infoBox(ex.toString(), "ERROR");
}
}
public void infoBox(String infoMessage, String location) {
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + location, JOptionPane.INFORMATION_MESSAGE);
}
}
Code where ResultSet is accessed:
public void searchFired(ActionEvent event) throws ClassNotFoundException {
try{
DBConnect db = new DBConnect();
db.open_Con();
ResultSet rs = db.get_data();
db.close_Con();
while (rs.next())
{
study_struct study = new study_struct();
ObservableList<String> row = FXCollections.observableArrayList();
study.setStudy_number(rs.getInt(1));
row.add(rs.getString(1));
study.setCustomer_id(rs.getInt(2));
study.setShop_order(rs.getInt(3));
study.setProduct(rs.getString(4));
study.setGmax_results(rs.getString(5));
study.setGmax_average(rs.getDouble(6));
study.setHic_results(rs.getString(7));
study.setHic_average(rs.getDouble(8));
study.setSensor_data_x(rs.getString(9));
study.setSensor_data_y(rs.getString(10));
study.setDescription(rs.getString(11));
study.setGauge(rs.getString(12));
study.setAppraiser(rs.getString(13));
study.setStudy_name(rs.getString(14));
row.add(rs.getString(14));
study.setTimestamp(rs.getString(15));
row.add(rs.getString(15));
study.setWeight(rs.getString(16));
found_studies.add(study);
search_table.add(row);
}
resultsGrid.setItems(search_table);
}
catch (SQLException ex)
{
}
}
As an extension to JoshDM's answer...
You need to make sure that you keep the connection open until you are finished with it, but you should, also, make every attempt to ensure that the connection is closed properly...
public void searchFired(ActionEvent event) throws ClassNotFoundException {
// This needs to be declared out side the try/catch so we can
// reference it later...
DBConnect db = new DBConnect();
try {
// Open the connection
db.open_Con();
// Get the data
ResultSet rs = db.get_data();
// Process the data
while (rs.next()) {
//...Trimmed for space ;)
}
resultsGrid.setItems(search_table);
} catch (SQLException ex) {
// It's never a good idea to "consume" exceptions,
// if you're not going to re-throw it, you should it at least
// log it
ex.printStackTrace();
} finally {
// Make every attempt to close the connection now we're finished with it...
try {
db.close_Con();
} catch (Exception e) {
}
}
}
Without seeing the code calling your get_data() method, which you should post, I will suspect you need to extract your data from your ResultSet before you close the connection.
Here is an example of how to work this appropriately:
http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzaha%2Fprepex.htm
EDIT: Based on your newly-posted code:
DBConnect db = new DBConnect();
db.open_Con();
ResultSet rs = db.get_data();
db.close_Con();
You are closing the connection right after you get the rows, this closes your ResultSet and flushes your data.
Iterate through the data, THEN call db.close_Con().
What you really want is a take on this:
CustomDataContainer data = new CustomDataContainer();
Connection conn = null;
PreparedStatement prep = null;
ResultSet rs = null;
try {
conn = getConnection(); // method returns a connection to your DB
prep = conn.prepareStatement(STRING_REPRESENTING_YOUR_STATEMENT);
rs = prep.executeQuery();
while (rs.next()) {
data.addData(rs.getString(1));
}
} catch (Exception ex) {
ex.printStackTrace();
// re-throw ex
} finally {
try { rs.close(); } catch (Exception ignore) {}
try { prep.close(); } catch (Exception ignore) {}
try { conn.close(); } catch (Exception ignore) {}
}
return data;

Java database application

Can someone help me with this: I'm making a java database application and I want to put my methods for select,insert,update and delete into separated class so they can be called from another classes and reused.
Till now I managed to separate only methods for update and delete and for insert when not using prepared statement. Problem I'm encountering is how to return data's when doing select from database and put them into table.
Here are my update and delete method's in Queries class:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.Konekcija.Konekcija;
public class Queries {
Konekcija konekcija = new Konekcija();
public void updateTable(String sqlQuery){
Connection conn = null;
Statement st = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
st.executeUpdate(sqlQuery);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void deleteFromTable(String sqlQuery){
Connection conn = null;
Statement st = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
st.executeUpdate(sqlQuery);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
P.S. Connection properties are in another class "Konekcija"
You should create a collection and populate it with the results of the query, it should look something like:
List<Foo> selectFoos(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("select * from foo");
try {
ResultSet resultSet = ps.executeQuery();
try {
List<Foo> foos = new ArrayList<Foo>();
while (resultSet.next()) {
Foo foo = new Foo();
// use resultSet methods get... to retrieve data from current row of results
// and populate foo
foos.add(foo);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
return foos;
}
try executeQuery method. in the java doc for "resultset" class you will find a example:
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
Return data for "select from table" would be ResultSet.
You may return the ResultSet to caller and get values (or)
Inside the "Select" method of Queries class retrieve the data from resultset and set it some VO object and add this VO to collection and return the collection (assuming you will get more than one row in ResultSet). For example if you are querying User table, create Java bean class "User" with get/set methods. Set retrieved values to this bean and return it.
//Create User class with get/set in some package.
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
ResultSet rs=st.execute(sqlQuery);
//Instantiate user class
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + String fName = rs.getString("firstName");
User myUser = new User();
myUser.setFirstName(fName);
}
NOTE: This code is hand typed. There may be syntax errors. Please use it as starting point.

Categories