如何在Java中创建全局MySQL连接方法

时间:2017-03-03 19:30:41

标签: java mysql javafx

我试图创建一个需要连接到MySQL DB的JavaFX应用程序,并执行用户名和密码检查(Login)以及其他CRUD应用程序。下面是我的Java类来连接和检查用户名和密码。但是,我不认为这是专业的每次我需要确保用户连接到数据库或执行其他CRUD活动我必须创建这整个步骤。 .. 是否有更专业的方法可以从任何地方访问创建全局方法,以便我可以调用它来为我做数据库连接?

public void LoginButtonHandler(ActionEvent event){

    user.setUsername(username.getText().trim());
    user.setPassword(password.getText().trim());
    String Username = user.getUsername();
    String Password = user.getPassword();

    try{           
        Class.forName("com.mysql.jdbc.Driver");  // MySQL database connection
        Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/airinvoice?" + "user=root&password=*******");     
        PreparedStatement pst = conn.prepareStatement("Select * from users where username=? and password=?");
        pst.setString(1, Username); 
        pst.setString(2, Password);
        ResultSet rs = pst.executeQuery();                        
        if(rs.next())   {
            Date dNow = new Date( );
            System.out.println("logged in with username: "+Username+" "+dNow);

            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Notification");
            alert.setHeaderText("you are logged in successfully");
            alert.setContentText("you are logged in as "+Username);
            alert.show();
        }         
        else{
            System.out.println("error logging in !");
            Alert erroAlert = new Alert(AlertType.INFORMATION);
            erroAlert.setTitle("Notification");
            erroAlert.setHeaderText("login unsuccessful");
            erroAlert.setContentText("check your username or password");
            erroAlert.show();
        }         
    }
    catch(Exception e){
        e.printStackTrace();
    }
}//end method LoginButtonHandler

1 个答案:

答案 0 :(得分:1)

您可以创建一个连接到数据库的单独类,例如:

import java.sql.*;

public class DBConnection {

  static final String DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost/yourDatabaseName";
  static final String DB_USER = "root";
  static final String DB_PASSWORD = "";
  Connection connection;

  public DBConnection(){
    connect();
  }

  public void connect(){
    try{
      Class.forName(DRIVER);
      connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }catch(SQLException|ClassNotFoundException e){
      System.out.println("ERROR connecting to database!");
      System.out.println(e.toString());
    }
  }

  public ResultSet select(String query){
    try{
      Statement statement = connection.createStatement();
      ResultSet result = statement.executeQuery(query);
      return result;
    }catch(SQLException e){
      System.out.println("ERROR while executing select query!");
      System.out.println(e.toString());
      return null;
    }
  }

  public int update(String query){
    try{
      Statement statement = connection.createStatement();
      return statement.executeUpdate(query);
    }catch(SQLException e){
      System.out.println("ERROR while executing update query");
      System.out.println(e.toString());
      return -1;
    }
  }

  public int delete(String query){
    try{
      Statement statement = connection.createStatement();
      return statement.executeUpdate(query);
    }catch(SQLException e){
      System.out.println("ERROR while deleting line!");
      System.out.println(e.toString());
      return -1;
    }
  }

  public void close(){
    try{
      connection.close();
    }catch(SQLException e){
      System.out.println("ERROR while closing connections!");
      System.out.println(e.toString());
    }
  }

}