0

我已经开始尝试一些东西,以便我可以将 mysql 数据库与 Java 一起使用。首先,我对此有一些疑问。

我在 PHP 开发中经常使用 mysql,但从未使用过 Java。我可以使用 MAMP 带来的 MySQL,还是必须单独安装它?

第二..我在教程的帮助下创建了这段代码,但我得到的唯一输出是

com.mysql.jdbc.Driver

我用于此的代码您可以在下面找到:

package Databases;

import java.sql.*;

public class MysqlConnect{

/* These variable values are used to setup
the Connection object */

 static final String URL = "jdbc:mysql://localhost:3306/test";
 static final String USER = "root";
 static final String PASSWORD = "root";
 static final String DRIVER = "com.mysql.jdbc.Driver";

 public Connection getConnection() throws SQLException {
    Connection con = null;
    try {
       Class.forName(DRIVER); 
       con = DriverManager.getConnection(URL, USER, PASSWORD);
    }
    catch(ClassNotFoundException e) {
       System.out.println(e.getMessage());
       System.exit(-1);
    }
    return con;
 }

 public void getEmployees() {
    ResultSet rs = null;
    try {
       Statement s = getConnection().createStatement();
       rs = s.executeQuery("SELECT id, name, job_id, location FROM person");
       System.out.format("%3s %-15s %-7s %-7s%n", 
          "ID", "NAME", "JOB ID", 
            "LOCATION");
       System.out.format("%3s %15s %7s %7s%n", 
          "---", "---------------", 
            "-------", "--------");

       while(rs.next()) {
          long id = rs.getLong("id");
          String name = rs.getString("name");
          long job = rs.getLong("job_id");
          String location = rs.getString("location");
          System.out.format("%-3d %-15s %7d %5s%n", 
             id, name, job, location);
       }
    }
    catch(SQLException e) {
       System.out.println(e.getMessage());
       System.exit(-1);
    }
 }
}
4

2 回答 2

7

它来自以下块:

catch(ClassNotFoundException e) {
   System.out.println(e.getMessage());
   System.exit(-1);
}

这是处理异常的一种非常糟糕的方式。您只是在打印异常消息。你不知道发生了什么。而是直接抛出它(最终会得到一个很好的堆栈跟踪),或者单独打印一个更具描述性的消息以及异常消息,例如

catch(ClassNotFoundException e) {
   System.out.println("JDBC driver class not found in runtime classpath: " + e.getMessage());
   System.exit(-1);
}

如何修复特定异常实际上是第二个问题(有一个非常明显的答案:只需将包含 JDBC 驱动程序类的 JAR 文件放在运行时类路径中),但是,你可能会发现这个迷你教程很有帮助:将 Java 连接到MySQL 数据库


与具体问题无关,我不确定您正在阅读哪个教程,但我会持保留态度。除了糟糕的异常处理之外,它还getEmployees()通过从不关闭结果集、语句和连接来泄漏方法中的数据库资源。这也绝对不是一个好习惯。如何做到这一点也已经包含在前面链接的迷你教程中。另请参阅:在 JDBC 中应多久关闭一次连接、语句和结果集?

于 2012-12-19T20:39:15.537 回答
0

是的,您需要在本地或远程安装 MySQL 服务器。

如果您还从 MySQL 下载页面下载了 jdbc Driver jar,则该代码将可用。并且您使用正确的用户名和密码配置了您的 MySQL 实例。

于 2012-12-19T20:44:38.390 回答