database connection not working in jar, but does work in eclipse

六月ゝ 毕业季﹏ 提交于 2020-01-06 08:22:12

问题


I have created a simple database in MYSQL, which I am trying to pull data from in a java program written in Eclipse. When I run the program in eclipse, it pulls out the data fine, but when I export the program into a runnable JAR, it just won't work!!

I have addedthe mysql connector by using the "add External Archive" feature in the build path, and have checked that its there by using

System.out.println("classpath = " + System.getProperty("java.class.path"));

which gives the results: classpath = C:\Users\Andy\workspace\test2\bin;C:\Users\Admin\Desktop\mysql-connector-java-5.1.16\mysql-connector-java-5.1.16-bin.jar

I have also opened up the exported JAR file and have seen that the connector has been added.

Here is the code that I am using:

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

import javax.swing.JOptionPane;



public class test
{
    public static void main(String args[])
{
    try
    {

        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cambridge","root","P@ssw0rd");
        System.out.println("classpath = " + System.getProperty("java.class.path"));

        Statement stmt = dbConn.createStatement();

        String strSQL = "Select * from customer_details";

        ResultSet rs = stmt.executeQuery(strSQL);

        ResultSetMetaData rsmd = rs.getMetaData(); 

        int nCol = rsmd.getColumnCount();

        while(rs.next())
        {
            for(int col=1; col<=nCol; col++)  
            {
                System.out.print(rs.getString(col));
                JOptionPane.showMessageDialog(null, rs.getString(col));
            }

            System.out.println();
        }

        System.out.println();

        dbConn.close();  
    }
    catch (Exception excp)
    {
        excp.printStackTrace();
    }
}
}

Thanks in advance for any help you can offer!!!


回答1:


FINALLY GOT IT!!!

I did the following:

Window -> Preferences -> Java -> Build Path -> Classpath Variables

then clicked on new, entered a name, then clicked on file and navigated to the mysql connector, and then hit ok!!

Not entirely sure why this worked, but when I did pretty much the same, but for an individual project didn't, but it worked, and thats the main thing!!

Thanks to everyone who responded and offered me some help. It took me a while, but I got there in the end!! :o)



来源:https://stackoverflow.com/questions/6247591/database-connection-not-working-in-jar-but-does-work-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!