我試圖通過文件屬性建立與mysql數據庫的連接,然後從servlet運行信息。我的Connection類看起來是這樣的:無法通過java類連接到數據庫
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
。 有人能幫我解決嗎?
錯誤登錄? – 11684
1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)請爲代碼塊使用一致的邏輯縮進。 –
Per Alexander Georgii-Hemm - 所以變量「連接」爲空然後呢?你有沒有檢查你使用的是正確的端口? –