DB.properties内容:
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/demo
userName=root
password=admin88
Java代码:
package util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBC {
static JDBC j;
Properties p;
Connection conn;
public static JDBC getInstance(){
if(j==null){
j=new JDBC();
}
return j;
}
public JDBC(){
//读取配置文件
try {
p.load(JDBC.class.getResourceAsStream("/DB.properties"));
//加载数据库的驱动类
Class.forName(p.getProperty("driver"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("没有驱动");
e.printStackTrace();
}
}
public Connection getConnection(){
try {
if(conn==null||conn.isClosed()){
conn=DriverManager.getConnection(p.getProperty("url"),p.getProperty("userName"),p.getProperty("password"));
System.out.println("连接成功!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void close(Connection conn,Statement stmt,ResultSet rs ){
try {
if(rs!=null){
rs.close();
}if(stmt!=null){
stmt.close();
}if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
疑惑:使用main函数测试会抛出空指针异常
Exception in thread "main" java.lang.NullPointerException
at util.JDBC.<init>(JDBC.java:24)
at test.ConnTest.main(ConnTest.java:7)
难道只能用junit单元测试么?