我正在尝试通过文件属性与mysql数据库建立连接,然后从servlet运行信息。我的Connection类看起来像这样:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
当我运行它时,它没有显示连接未建立的错误,但是当它到达
时public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
它抛出java.lang.NullPointerException
。
任何人都可以帮助我吗?
答案 0 :(得分:0)
代码没有问题。 检查你的传递参数......
检查样本
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}