我已经开始尝试一些东西,以便我可以将Java数据库与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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它来自以下块:
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
这是处理异常的一种非常糟糕的方式.您只是打印异常消息.你不知道发生了什么.而只是抛出它(最终会有一个很好的堆栈跟踪),或者单独打印一条更具描述性的消息,例如异常消息,例如
catch(ClassNotFoundException e) {
System.out.println("JDBC driver class not found in runtime classpath: " + e.getMessage());
System.exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
如何修复特定的异常反过来实际上是第二个问题(有一个非常明显的答案:只是将JAR文件包含在运行时类路径中的JDBC驱动程序类),但是ala,你可能会发现这个迷你教程很有用:将Java连接到一个MySQL数据库.
与具体问题无关,我不确定你在那里阅读哪个教程,但我会把它带到一块盐.除了糟糕的异常处理之外,它还getEmployees()通过永远关闭结果集,语句和连接来泄漏方法中的DB资源.这绝对不是一个好习惯.如何做到这一点也已在前面提到的迷你教程中介绍过.另请参阅:在JDBC中关闭Connection,Statement和ResultSet的频率如何?
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |