0

My partner and I are working on a project in which we have to connect to a MySQL database from a Java program.

We're are able to connect to the database when it's deployed on the localhost but the project will be run on another computer as well, and we have to make a .jar file.

Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","");
        st = con.createStatement();
        rs = st.executeQuery("select * from program");

We used the above code to access the database running on localhost.

Is there a way to make the database portable? Like is there a way that we can include it in the .jar file? Is it gonna perform the same way it performs on the IDE? Do we need to make some special adjustments? Any help would be amazing.

iraleigh
  • 185
  • 6
  • I'm not sure if it's what you are looking for, but there is this: https://stackoverflow.com/a/12027746/13493555 – s6xy May 07 '20 at 19:43

2 Answers2

0

If the server the localhost is running on is available from the web, then you can substitute your IP address. If not, you will have to install the MySQL DB somewhere that is accessible from the web and use that IP address.

B Mc
  • 1
  • 1
0

If you need this to be portable code, then the connection string needs to be configurable and not hardcoded.

Here are a couple ways to do this:

  1. Have the Java program look for property either in a properties file or as a System property (String connectionString = System.getProperty("mysql.connection");)
  2. Have the Java program accept the connection string from the args array in the main method

Doing this allows the user of the .jar file to define how they connect to the database, whether it be local or remote.

Along those same lines, you may want to make the username and password configurable as well.

iraleigh
  • 185
  • 6