繁体   English   中英

Java中的调用方法

[英]Calling method in Java

我想通过使用aplikacja.properties文件中的主机,用户名和密码与mysql db连接。 但是我有问题bcs这些方法返回null,我不知道为什么?

getHost()

getUsername()

获取密码()

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);
    }
}

感谢帮助。

我看不到任何调用readConnectionParam方法的代码,这是唯一可以初始化在返回null方法中返回的变量的东西。 称它为。

您应该首先初始化调用该方法的vars

readConnectionParam 

内部主要

您必须调用readConnectionParam()方法,因为这些字段在此处已初始化。

尝试:

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

由于方法readConnectionParam()抛出Exception将以上代码包含在try catch

采用 -

baza.readConnectionParam();

Mysql baza = new Mysql();

声明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM