0

Thanks in advance for any help. I am creating a Database - Client application using java in Eclipse. I am using MySQL 5.6 for my database. I have a method to create and return a Connection Object that I will use for querying the database, and a method to return all of the rows in the table as a JSON array. The problem comes in the query method when trying to call the connection method.

at: try{ con.getDBConnection(); its telling me there is an error for getDBConnection(); and the suggestions that it gives is to add cast to 'con'.

and I can't get the query method to compile from the main method.

package binaparts.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.*;
import org.json.JSONArray;

import binaparts.util.ToJSON;

public class returnAllParts extends DBConnect{

    public JSONArray queryReturnAllParts() throws Exception{

        PreparedStatement query = null;
        Connection con = null;

        ToJSON converter = new ToJSON();
        JSONArray json = new JSONArray();

        try{
            con.getDBConnection();
            query = con.prepareStatement("SELECT * " + "from `parts list`" );

            ResultSet rs = query.executeQuery();

            json = converter.toJSONArray(rs);
            query.close();
        }catch(SQLException SQLex){
                SQLex.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            if(con != null){
                con.close();
            }
        }
        return json;
    }
}

dao package code below:

package binaparts.dao;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.mysql.jdbc.PreparedStatement;

public class DBConnect {

    private Statement st = null;
    private ResultSet rs = null;
    private Connection con = null;  
    private PreparedStatement pst = null;

    private String serverName = "localhost";
    private String portNumber = "3306";
    private String dbms = "mysql";
    private Object userName = "dwilson";
    private Object password = "abc";

    public Connection getDBConnection() throws SQLException {

        Properties connectionProps = new Properties();
        connectionProps.put("user", this.userName);
        connectionProps.put("password", this.password);

            try{
                con = DriverManager.getConnection("jdbc:" + this.dbms + "://" + this.serverName + ":" + this.portNumber + "/", connectionProps);
            }catch(Exception ex){
                ex.printStackTrace();
                con = null;
            }finally{
                if(con != null){
                     System.out.println("Connected to database");
                }
            }
        return con;
    }
    public String getUser(){
        try{
            DatabaseMetaData dmd = con.getMetaData();
            String username = dmd.getUserName();
            //System.out.println("Current User: "+username);
            return username;
        }catch(Exception ex){
            System.out.println(ex);
            ex.printStackTrace();
            return null;
        }
    }
}

main method below:

public class Main{

    public static void main(String[] args){

        DBConnect con = new DBConnect();
        try {
            con.getDBConnection();
            System.out.println(con.getUser());
            System.out.println(con.queryReturnAllParts());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //Login loginGUI = new Login();
        //MainFrames m = new MainFrames();
        //m.displayGUI();
    }
}

The System.out.println(con.getUser()); does work

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Danny
  • 21
  • 2
  • 8

3 Answers3

3

In your returnAllParts#queryReturnAllParts method, change

con.getDBConnection();

By

con = getDBConnection();

The problem is that con is a variable from java.sql.Connection and it doesn't have a getDBConnection method. Since your current returnAllParts class extends DBConnect class, it can access to the public Connection getDBConnection method with no problems.

The System.out.println(con.getUser()); does work

This is because in your Main#main class, you have declared DBConnect con. Do not confuse this variable with the con variable declared in other methods.


Not directly related to the problem, but I suggest you some improvements to your current code/design:

  • Change the name of your returnAllParts class for something more meaningful for future readers (even you in some days or weeks will become in a future reader of your code). From reading your code, it looks like this class should be renamed to PartList.
  • Use a Database connection pool instead of manually get your connections. There are libraries that handle this for your like BoneCP
  • Probably you're new to programming, so it would be better that you start in the right way and develop your application in layers (further reading: Multitier architecture). With this basis, we can say that a DAO (or data service, depends how you name it) should only contain the methods to access and retrieve the data in a way other clients could consume it as they want/need, so it would be better returning a List<PartList> object and that another layer in your application (probably the closest to presentation) will apply the transformation from your objects to a JSON String.
  • For a design point of view, it would be way better if your database access objects uses a DBConnect object instead of extending from it. In this way, you could have a single DBConnect object per database connection configuration associated to all the related DAOs.
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • going from con. to con = fixed the problem inside of the returnAllParts method - thanks. I was planning on using the returnAllParts class to hold the methods for querying the database, I was just testing the initial method. Would something along the lines of DatabaseQuery be more appropriate? – Danny Aug 08 '13 at 14:31
  • @Danny this really depends on what the class will do. If the `returnAllParts` is associated with any kind of query, then `DatabaseQuery` would be a proper name, if is just related with the `part list` table, then `PartListDAO` would be a better name. – Luiggi Mendoza Aug 08 '13 at 14:35
  • +1 The improvement suggestions are more helpful in the long run than the question/answer themselves. – Sotirios Delimanolis Aug 08 '13 at 14:46
  • I am fairly new to writing actual java applications as opposed to bits of code to try things out, so improvement suggestions are much appreciated. Thanks! – Danny Aug 08 '13 at 14:48
1

In this code

    PreparedStatement query = null;
    Connection con ;

    ToJSON converter = new ToJSON();
    JSONArray json = new JSONArray();

    try{
        con.getDBConnection();

the variable con is of type java.sql.Connection, not DBConnect. That type does not have a getDBConnection() method. I believe you meant to use

 con = this.getDBConnection(); 

in your first returnAllParts class (which extends DBConnect). (Please use Java naming conventions.)

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    +1 and OP should also consider using a data source. I mean if someone has already made efforts to create DB helper classes, why not implement connection pooling as well? – Ravi K Thapliyal Aug 08 '13 at 14:30
  • @Ravi There are a few redundant things in his code. OP should start with setting up and using DataSource as you suggest. – Sotirios Delimanolis Aug 08 '13 at 14:32
  • I was trying to lookup how to implement the DataSource class but I couldn't quite figure it out, since I am not using a webservice tier to go through. I am planning on making a properties file that can be set from the application gui eventually. – Danny Aug 08 '13 at 14:42
  • @Danny You don't need to be in a webservice tier to create a `DataSource`. Check out the class [`BasicDataSource`](http://commons.apache.org/proper/commons-dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html) from Apache commons-dbcp. – Sotirios Delimanolis Aug 08 '13 at 14:44
  • 1
    @Danny you can use BoneCP for that as well, note the updates on my answer. – Luiggi Mendoza Aug 08 '13 at 14:45
0

In your "returnAllParts" method you define Connection con ;.

That Connection is a java.sql.Connection object and it doesn't have the method you seek. Remove it.

Xabster
  • 3,710
  • 15
  • 21
  • I must have messed that up in formatting the post. It should have been Connection con = null; I have updated the source code – Danny Aug 08 '13 at 14:32