2

I have class "DBDemoFrame" with main method and class "DBManager" where I connect to database. I want build login form when I can login as a different mysql user.

package pl.kti.dbdemo.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBManager {
    public static String _host = "127.0.0.1";
    public static String _port = "3306";
    public static String _user = "root";
    public static String _pass = "12345";
    public static String _db = "product";

    private static Connection connection;

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        if (connection == null) {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://" + _host + ":" + _port + "/" + _db + "";
            connection = DriverManager.getConnection(url, _user, _pass);
        }
        return connection;
    }
}

In "DBDemoFrame" I have method like this (I'm not sure if it's useful in this case)

protected void sendQuery(String query) {
    try {
        if (query.length() > 6 && 
            ( 
                query.substring(0, 6).equalsIgnoreCase("insert") || 
                query.substring(0, 6).equalsIgnoreCase("update") ||
                query.substring(0, 6).equalsIgnoreCase("delete") 
            )
        ) {
                Statement stmt = DBManager.getConnection().createStatement();
                stmt.executeUpdate(query);
                _tableModel.setResultSet(null);
                stmt.close();
            } else if ((query.length() > 6) && (query.substring(0,6).equalsIgnoreCase("select"))){
                // create SQL statement and execute query read from the _editor
                Statement stmt = DBManager.getConnection().createStatement();
                ResultSet queryResult = stmt.executeQuery(query);
                // pass the resultSet to the table model (use setResultSet method from the model)
                _tableModel.setResultSet(queryResult);
                // close the resultSet and statement
                queryResult.close();
                stmt.close();
            }
            else
            {
                Statement stmt = DBManager.getConnection().createStatement();
                stmt.execute(query);
                stmt.close();
            }
        } catch (Exception e) {
            _editor.setText(e.getMessage());
        }
    }
}
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119

0 Answers0