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?