在java的整个程序中使用一个sql连接对象

q8l4jmvw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(242)

我想用sql用户名和密码登录,因为它很容易给数据库的权限。连接成功,但我想在整个程序中使用相同的url和凭据,但不知道如何使用。我有两个不同的类下面的代码
这是我的登录页面,工作正常

public class login {
    static String connectionUrl;
    @FXML
    private TextField loginusername_txt;
    @FXML
    private TextField loginpassword_txt;
    public final String url() throws SQLException {
        return connectionUrl = "jdbc:sqlserver://WIN\\SQLEXPRESS:1433;database=itinventory;" + "user=" + loginusername_txt.getText() + ";" + "password=" + loginpassword_txt.getText() + ";";

    }
    public final Connection conn() throws SQLException {
        Connection connect = DriverManager.getConnection(url());
        return connect;
    }
    public void connection(ActionEvent Event) throws Exception {

        try (Connection connect = DriverManager.getConnection(url());) {
            // Code here.
            Stage main = new Stage();
            Parent root = FXMLLoader.load(getClass().getResource("/application/main.fxml"));

            Scene scene = new Scene(root, 500, 500);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            main.setScene(scene);
            main.show();

            loginusername_txt.clear();
            loginpassword_txt.clear();

        }
        // Handle any errors that may have occurred.
        catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

//another class coding is
//full code for controller class is                                                                                                        public class controller {
login log = new login();
Stage main = new Stage();                                                                                                                 @FXML
private MenuItem mainip_menuitem;
public void laptop(ActionEvent Event) throws Exception
{
    AnchorPane root = FXMLLoader.load(getClass().getResource("/application/laptop.fxml"));
    samewindow(root);
}
@FXML
AnchorPane main_pain;
public void samewindow(AnchorPane samepane)
{
    main_pain.getChildren().setAll(samepane);
}
@FXML
private ComboBox laptopos_combo;
public void filloscombo() throws SQLException
{
    String query="Select * from operatingsystem";
    PreparedStatement pst = log.conn().prepareStatement(query);
            //.prepareStatement(query);
    ResultSet os = pst.executeQuery();
    while(os.next())
    {
        System.out.println(os);
    }
}

在运行第二个代码时,它显示此错误:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: 
    java.lang.reflect.InvocationTargetException
Caused by: java.lang.reflect.InvocationTargetException

Caused by: java.lang.NullPointerException
    at application.login.url(login.java:24)
    at application.login.conn(login.java:29)
    at application.controller.filloscombo(controller.java:61)
holgip5t

holgip5t1#

田野 loginusername_txt 以及 loginpassword_txt 尚未初始化,构造函数正在访问它。你需要初始化它,而不仅仅是声明它。

相关问题