-1

I'm having trouble using the JDBC Connector. I got it to work in Eclipse but it doesn't seem to work from command line. I re-named the connector "driver.jar" and put it into a /lib directory in the folder of my Main class. I even set the class path to the /lib/driver.jar but that doesn't seem to do the trick. Can someone please advise me on how to setup the JDBC so that I can connect to a MySQL database. This is really frustrating.

Sample Code:

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

public class Main {
    public static void main(String args[]) {
        // Database credentials
        Connection conn = null;
        String url = "jdbc:mysql://localhost/";
        String db = "db";
        String driver = "com.mysql.jdbc.Driver";
        // Connect to database
        try {
            Class.forName(driver);
            System.out.println("HELLO");
            conn = DriverManager.getConnection(url+db,"root","");
            System.out.println("Success");
            } catch(Exception e) {
            return;
        }
    }

}
4

4 回答 4

3

我同意@Mark Rotteveel 将 jar 文件放入 lib\ext\ 不是一个优雅的解决方案。

您可以尝试@AVD 的建议,但使用“:”作为分隔符,因为您在 Mac OSX 上运行程序。

示例(假设您的 Main.class 和 lib/ 在同一文件夹中):

>java -cp .:./lib/driver.jar Main
于 2012-06-30T08:05:38.553 回答
0

试试下面的代码,要获得连接,请在 getConnection() 方法中用你的用户名和密码替换。尝试解决这个问题,如果它适合你,那么请看看你的代码有什么问题。

public class DBDiary {

    Connection conn;


    public DBDiary(){

        this.getConn();

    }

    public Connection getConn(){

        try {
            conn = getConnection();

        } catch (SQLException e) {

            System.out.println("Connection Couldnt be Obtained");
        }
           return conn;
    }


    public static Connection getConnection() throws SQLException {

        String drivers = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "root";

        System.setProperty(drivers,"");

        return DriverManager.getConnection(url,username,password);

    }

   }
于 2012-06-30T04:24:35.887 回答
0

如果您正在开发桌面应用程序,则需要将其放入 Eclipse 中的项目构建路径中

如果您正在开发 Web 应用程序,例如 Web 服务或其他东西,那么您需要将此文件添加到该文件 project_folder\WebContent\WEB-INF\lib 中,它将起作用。然后你可以像@Arun P Johny 所说的那样与 mysql 通信。还是有问题再写信给我。

于 2012-06-30T04:57:53.033 回答
-4

我希望,它无法找到 MYSQL 的驱动程序库文件。

尝试这个

复制 JRE/lib/ext 中的 driver.jar

前任。C:\Program Files\Java\jre1.5.0\lib\ext

于 2012-06-30T04:19:53.230 回答