0

I have a client-server-database set-up in Java and I am figuring out a way to set up the server code and database connectivity code together, I have the following 2 classes (not connected as we speak):

Class to connect to the database and execute a random query:

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

public class DatabaseConnection {

    public static void main(String[] args) {

        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }

        Connection conn = null;

        try {
            conn =
               DriverManager.getConnection("jdbc:mysql://localhost:3306/test" +
                                           "?user=root&password=test");


          
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        
       
        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM Authentication");

            // or alternatively, if you don't know ahead of time that
            // the query will be a SELECT...

            if (stmt.execute("SELECT * FROM Authentication")) {
                rs = stmt.getResultSet();
            }
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnsNumber = rsmd.getColumnCount(); 
            while (rs.next()) {
                for (int i = 1; i <= columnsNumber; i++) {
                    if (i > 1) System.out.print(" ");
                    String columnValue = rs.getString(i);
                    System.out.print(columnValue );
                }
                System.out.println("");
            }
            
        }
        catch (SQLException ex){
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        finally {
            // it is a good idea to release
            // resources in a finally{} block
            // in reverse-order of their creation
            // if they are no-longer needed

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) { } // ignore

                rs = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) { } // ignore

                stmt = null;
            }
        }
        
    }

}

Server class:

import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;

public class MultipleServer {
    public static void main(String[] args) throws IOException {
        Scanner scan=new Scanner(System.in);
        
        System.out.println("Enter the port number on which the server should be listening on");
        int portnum=scan.nextInt();
        ServerSocket serverSocket = new ServerSocket(portnum);

        // Server keeps on receiving new Clients
        while (true) {
            Socket clientSocket = null;
            try {
                // ServerSocket waits for a Client to connect
                clientSocket = serverSocket.accept();

                System.out.println("A new client is connected : " + clientSocket);

                // Receiving input and sending output to Client
                DataInputStream inputFromClient = new DataInputStream(clientSocket.getInputStream());
                DataOutputStream outputToClient = new DataOutputStream(clientSocket.getOutputStream());

                System.out.println("Assigning new thread for this client");

                System.out.println("-----------------------------------------------------------------------------------");

                // Create a new Thread object for the Client
                Thread thread = new ClientHandler(clientSocket, inputFromClient, outputToClient);
                thread.start();

            } catch (Exception e) {
                clientSocket.close();
                e.printStackTrace();
            }
        }
    }
}

// ClientHandler class
class ClientHandler extends Thread {
    final Socket clientSocket;
    final DataInputStream inputFromClient;
    final DataOutputStream outputToClient;

    // Constructor
    public ClientHandler(Socket clientSocket, DataInputStream inputFromClient, DataOutputStream outputToClient) {
        this.clientSocket = clientSocket;
        this.inputFromClient = inputFromClient;
        this.outputToClient = outputToClient;
    }

    @Override
    public void run() {
        // Variables
        String received;
        String toreturn;
        while (true) {
            try {
                // Initiate communication with Client
                outputToClient.writeUTF("Type Exit to terminate connection.");

                // Receive the answer from Client
                received = inputFromClient.readUTF();

                // Receiving Exit closes the connection and breaks the loop
                if (received.equals("Exit")) {
                    System.out.println("-----------------------------------------------------------------------------------");
                    System.out.println("Client " + this.clientSocket + " sends exit...");
                    System.out.println("Closing this connection.");
                    this.clientSocket.close();
                    System.out.println("Connection closed");
                    break;
                }

                // Send to Client what is requested
                switch (received) {

                default:
                    outputToClient.writeUTF("Invalid input");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // Closing resources
            this.inputFromClient.close();
            this.outputToClient.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I have a few queries I need to execute, my idea was to have each one in a separate method and call it from the client while having the input needed as a parameter, however, if I do this, then the connection won't be established as it will be in the main() so do I just include in every method the code that connects my program to the server? or do I just merge this into one class?

Sergio
  • 275
  • 1
  • 15
  • Are you familiar with database connection pooling? You're not running in a JEE environment apparently but tools like [c3p0](https://github.com/swaldman/c3p0) can help. – stdunbar Dec 03 '21 at 17:10
  • 1
    Are you following an outdated and old tutorial? Your code looks very clumsy not using for example try-with-resources and other such things. I recommend having a look at a respectable source like [Baeldung](https://www.baeldung.com/java-jdbc). – Kayaman Dec 03 '21 at 17:12
  • @Kayaman this is mostly from the MySQL official website – Sergio Dec 03 '21 at 17:18
  • @studnbar no, I am not – Sergio Dec 03 '21 at 17:19
  • 1
    @Sergio really? I guess they don't update it too often. It looks like an amateur wrote it. – Kayaman Dec 03 '21 at 17:21
  • Have you considered using a JEE environment (Tomcat, Wildfly, etc) for your code? As it is your code will likely work but you're spending a good amount of time and code on things that are done more easily in a different way. – stdunbar Dec 03 '21 at 17:45

1 Answers1

-1

No, you don't need new connection. You can reuse same connection multiple times.

talex
  • 17,973
  • 3
  • 29
  • 66
  • so where would the establishing connection code be then? – Sergio Dec 03 '21 at 17:08
  • if I keep it in main, I don't think it would be simply executed when I call a method other than the main (correct me if I am wrong), and the client could decided to invoke any method so I can't put it in a certain one knowing it is the first to be called – Sergio Dec 03 '21 at 17:09
  • 2
    Usually people use connection pool. It is library that will handle opening and closing connection for you. – talex Dec 03 '21 at 17:25