-1

I'm creating dynamic web project that I am working on /servlet app .keep getting this error . I've tried many methods.Still, the error persists. What is strange is if I start typing the package name eclipse actually auto-completes the class for me! how to resolve this issue...I'm getting error at "database" keyword in jsp code. it keep showing error: "DatabaseConnection cannot resolved."

[the red under line is the key word where I get error][1]

this is code of database

package com.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseConnection {

            //Creating Connection
            public static Connection connection;
    
            //Creating universal method to open connect will mysql database
            public static Connection getConnection() {
                try {
                    //Registering with mysql Driver
                    Class.forName("com.mysql.jdbc.Driver");
                    connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingsystem", "root", "Narend-10");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return (connection);
            }
    
            //Creating universal method to close connect will mysql database
            public static void CloseConnection() {
                if (connection != null) {
                    try {
                        connection.close();
                        connection = null;
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
            }
    
            //Creating universal method to query for retriving information
            public static ResultSet getResultFromSqlQuery(String SqlQueryString) {
                //Creating Resultset object
                ResultSet rs = null;
                try {
                    //Checking whether the connection is null or null
                    if (connection == null) {
                        getConnection();
                    }
                    //Querying the query
                    rs = connection.createStatement().executeQuery(SqlQueryString);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return rs;
            }
    
            //Creating universal method to query for inserting or updating information in mysql database
            public static int insertUpdateFromSqlQuery(String SqlQueryString) {
                int i = 2;
                try {
                    //Checking whether the connection is null or null
                    if (connection == null) {
                        getConnection();
                    }
                    //Querying the query
                    i = connection.createStatement().executeUpdate(SqlQueryString);
    
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return i;
            }
        }
    
    }

}

this code for jsp

<%
    ResultSet resultOrders=DatabaseConnection.getResultFromSqlQuery("select * from tblorders where order_status='Pending'");
   while (resultOrders.next()) {
         
%>


  [1]: https://i.stack.imgur.com/GJbtg.png

1 Answers1

0

Without a proper error message it's hard to exactly pinpoint the issue. Judging by the context I suppose you are just missing an import statement in your JSP. Try to import the Java Class like the following:

<%@ page import="com.connection.database" %>
<%
    ResultSet resultOrders = database.getResultFromSqlQuery("select * from tblorders where order_status='Pending'");
    while (resultOrders.next()) {
%>

I also saw that your coding style is really messed up. Let me also give you some hints on how to improve the readability of your code. Java is such a beautiful language for it to die with code quality.

Naming conventions: Class names: Capitalize the first letter of each word (PascalCase), e.g., DatabaseConnection. Method and variable names: Use camelCase, e.g., getResultFromSqlQuery. Constants: Use uppercase letters with underscores for separation, e.g., MAX_CONNECTIONS.

Indentation: Your whole namespace is indented by much too much, keep it consistent and decide for one of the following optimally as they are the most popular:

  • 2 spaces
  • 4 spaces
  • 1 tab

Self Documenting Code: Try to give your function and variable names generally a good and self explaining name so your code basically documents itself. This reduces random thrown in comments. Good code doesn't need comments.

Try to not place misleading comments: Consider the following in your code:

//Creating Connection
public static Connection connection;

Initially this looks like the connection itself is created and opened there, not just the object.

Create meaningful exceptions: Your exceptions are mostly just printing stack traces. Maybe try to instead give proper error logs since at the point of coding the exception, you know what went wrong. This will make debugging a breeze.

And finally but not least:

Use guard clauses: One specific case in your code I saw was:

//Creating universal method to close connect will mysql database
public static void CloseConnection() {
    if (connection != null) {
        try {
            connection.close();
            connection = null;
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

This is a lot of depth into a function without any reason. Instead this can be made more readable by doing:

//Creating universal method to close connect will mysql database
public static void CloseConnection() {
    if (connection == null) return;
    try {
        connection.close();
        connection = null;
    } catch (SQLException ex) {
        // proper error logging
    }
}

If you place the return at the end of the line is debatable. It's mostly personal preference.

Edit I forgot to mention that your namespace name is very unrepresentative. Try to choose something better for a namespace. (Unless you actually own "connection.com". Usually it should be something like the companies website as a prefix and then the class name. If you owned "example.com" as a company, you'd use "com.example.database". Try to keep it proper or unexpected things might happen in the future.

Good luck, hope I was of help.

kek5chen
  • 96
  • 10
  • Your revised `CloseConnection` method is incorrect. It only attempts to close the connection if `connection` is null, which will of course cause an NPE if `connection` is null. Presumably you want the first line to be `if (connection == null) return;` instead? – Luke Woodward Mar 18 '23 at 14:50
  • You're right. I wrote so much that i missed that detail when refactoring it. Thanks for mentioning it. – kek5chen Mar 19 '23 at 15:05