2013-03-15 81 views
0

我想通過使用來自文件aplikacja.properties的主機,用戶名和密碼與mysql db連接。但我有問題bcs那些方法返回null,我不知道爲什麼?Java中的調用方法

和getHost()

getUsername()

getPassword來()

getDb()

package aplikacja.mysql; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.Properties; 

public class Mysql { 

    private String host; 
    private String username; 
    private String password; 
    private String db; 

    public void readConnectionParam() throws FileNotFoundException, IOException { 
     Properties mysqlAplikacjaProperties = new Properties(); 
     FileInputStream mysqlPlik = new FileInputStream("aplikacja.properties"); 
     mysqlAplikacjaProperties.load(mysqlPlik); 
     host = mysqlAplikacjaProperties.getProperty("jdbc.host"); 
     username = mysqlAplikacjaProperties.getProperty("jdbc.username"); 
     password = mysqlAplikacjaProperties.getProperty("jdbc.password"); 
     db = mysqlAplikacjaProperties.getProperty("jdbc.db"); 
    } 

    public String getHost() { 
     return host; 
    } 

    public String getUsername() { 
     return username; 
    } 

    public String getPassword() { 
     return password; 
    } 

    public String getDb() { 
     return db; 
    } 

    public static void main(String[] args) throws SQLException { 

     Mysql baza = new Mysql(); 
     System.out.println(baza.getUsername()); 

     Connection polaczenie = null; 
     String driver = "com.mysql.jdbc.Driver"; 
     try { 
      Class.forName(driver).newInstance(); 
      polaczenie = DriverManager.getConnection(
        "jdbc:mysql://" + baza.getHost() + "/" + baza.getDb(), 
        baza.getUsername(), baza.getPassword()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     Statement statement = polaczenie.createStatement(); 
     String command = "INSERT INTO users (id, name, surname) VALUES (2, 'Tom', 'Suszek')"; 
     statement.executeUpdate(command); 
    } 
} 

感謝您的幫助。

回答

0

你必須調用readConnectionParam()方法,因爲thesse領域都在這裏初始化內。

嘗試:

Mysql baza = new Mysql(); 
baza.readConnectionParam(); 
System.out.println(baza.getUsername()); 

中包括一個try catch上面的代碼,因爲該方法readConnectionParam()拋出Exception小號

3

我沒有看到任何調用readConnectionParam方法的代碼,這是唯一可以初始化返回null的方法返回的變量的代碼。叫它。

0

你應該先初始化瓦爾調用方法

readConnectionParam 

主要

0

使用 -

baza.readConnectionParam(); 

Mysql baza = new Mysql(); 

聲明。