【发布时间】:2012-12-19 20:36:01
【问题描述】:
我已经开始尝试一些东西,以便我可以将 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);
}
}
}
【问题讨论】:
-
包含调用
getEmployees方法的代码。 -
您甚至会在哪里获得打印声明?我在您的代码中看不到它的合理位置。
-
打印异常的堆栈跟踪,你会看到什么问题
-
请不要乱改题,导致所有答案无效。如果您有新问题,请提出新问题。我已回滚您的无效编辑。