开发者

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

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();

     开发者_如何学C   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!!!


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜