抛出NullPointerException异常
package JDBC;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
public class TestJDBC {
public Connection getConnection() {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
Driver driver=null;
try {
driver = (Driver) Class.forName(driverClass).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
Connection connection=null;
try {
connection = driver.connect(jdbcUrl, info);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void main(String[] args) {
TestJDBC t = new TestJDBC();
Connection c = t.getConnection();
System.out.println(c);
}
}
抛出Exception in thread "main" java.lang.NullPointerException异常
jdbc.properties
要在与class同一目录,里面要存放driver/jdbcUrl等信息,且要真实有效的(与你的系统有关)
网上的程序不是拿来就能用的,你先必须看懂才可以
上一篇:谁能给推荐一个在线的思维课程呢