Home > Mobile >  How to set-up a client-server program and a database together in Java?
How to set-up a client-server program and a database together in Java?

Time:12-03

I need to create a program that has a client, server, and a database The client needs to input data into the database or query it via the server, I am using mySQL and JDBC to connect mySQL to my java code, however, I was wondering what the ideal set-up is.

For example, I am connecting to my database using the following code:

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

public class test2 {

    public static void main(String[] args) {
        
        String url = "jdbc:mysql://localhost:3306/CovidPreventation";
        String username = "test";
        String password = "test";

        System.out.println("Connecting database...");

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }
    
    }

}

I was wondering where this should really go, shall I have this in the server class or in a separate class that is connected to the server. It is the first time I do such a thing and I want my practices to be good so help is appreciated.

CodePudding user response:

all you need a jdbc driver, you can get it here: MVC Flow

Model
Model is responsible or maintaining data. It is actually connected to DB. So any data manipulation i.e. ADD/Update/Delete/Insert you want to do is done in model. Basically Models only talks with Controller and gives the needed data to controller. i.e. Model never communicates with Data directly.

View
Data representation i.e. UI (Html/CSS part) is done by View. Controller gives data to View which will be show to end user. i.e. View only speaks to controller.

Controller
Controller enables interaction between views and model. It does not have to worry about business logic. It will tell the model what should be done. After receiving Data from the Model it sends it to View.

  • Related