Creating jar file with MySQL JDBC Connector

So after trying to make a simpler method of executing some Java code that depends on MySQL JDBC drivers via CLI I came up with this solution. It basically involves 3 stages:

  1. Extract contents of MySQL JDBC connector (mysql-connector-java-5.1.28-bin.jar in this example)
  2. Create a manifest file and compile your Java files
  3. Package them all up nice and neatly into your very own jar

These steps assume you are in the correct directory with the required file(s) present when executing commands.

1. To extract the contents of the mysql-connector-java-5.1.28-bin.jar file you execute the following command:-

jar xf mysql-connector-java-5.1.28-bin.jar

This will put all the contents of the jar file in the current directory. This includes 3 directories (META-INFcom and org)

2. Create a manifest.txt file and compile your Java file(s).

The manifest just needs to include the main class of your program for this objective and will be written like so: ‘Main-Class: mainClass’ where you replace mainClass with the class name of your program containing the main() method (if you have a Java file called Dinosaur.java, you replace mainClass with Dinosaur).

a. Create the manifest file:-

echo Main-Class: Dinosaur>manifest.txt

b. Compile your Java file(s)

javac *.java

3. Finally, you need to put it all back together again in one big box …or jar

jar cvfm jarName.jar manifest.txt *.class META-INF com org

This will add all of the contents extracted from the MySQL JDBC Driver, your manifest information and any class files that were created via stage 2b.

To run this .jar file, use this command:-

java -jar jarName.jar

The code I am using for database connection testing and jar creation:-
import java.sql.*;
class className
{
public static void main(String[] args) throws Exception {
 Connection con = null;
 Statement st = null;
 ResultSet rs = null;
 int numberOfColumns=6;
 String url = "jdbc:mysql://host/database";
 String user = "username";
 String password = "password";
try {
 con = DriverManager.getConnection(url, user, password);
 st = con.createStatement();
 rs = st.executeQuery("SELECT * FROM table");
while (rs.next()) {
 for(int i=1; i<numberOfColumns;i++)
 {
 System.out.print(rs.getString(i) + " "); 
 }
 }
} catch (SQLException ex) {
 System.out.println(ex);
 } finally {
 try {
 if (rs != null) {
 rs.close();
 }
 if (st != null) {
 st.close();
 }
 if (con != null) {
 con.close();
 }
} catch (SQLException ex) {
 System.out.println(ex);
 }
 }
 }
}
Bookmark the permalink.

Comments are closed.