Create a class to connect to any database using jdbc

前端 未结 4 1223
长发绾君心
长发绾君心 2020-12-15 02:01

I am trying to design a Java swing application. I want to experiment and use an MVC type of architecture whereby my UI is separated from the actual logic to access data and

相关标签:
4条回答
  • 2020-12-15 02:35

    Just create a separate class and delegate to him a getting of connection to database:

    public class ConnectionManager {
        private static String url = "jdbc:mysql://localhost:3306/prototypeeop";    
        private static String driverName = "com.mysql.jdbc.Driver";   
        private static String username = "root";   
        private static String password = "triala";
        private static Connection con;
        private static String urlstring;
    
        public static Connection getConnection() {
            try {
                Class.forName(driverName);
                try {
                    con = DriverManager.getConnection(urlstring, username, password);
                } catch (SQLException ex) {
                    // log an exception. fro example:
                    System.out.println("Failed to create the database connection."); 
                }
            } catch (ClassNotFoundException ex) {
                // log an exception. for example:
                System.out.println("Driver not found."); 
            }
            return con;
        }
    }
    

    Then get the connection in a code as follows:

    private Connection con = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    
    con = ConnectionManager.getConnection();
    stmt = con.createStatement();
    rs = stmt.executeQuery(sql);
    
    0 讨论(0)
  • 2020-12-15 02:37

    You can either use fancier stuff like Hibernate or if your database usage is simple then you can try Commons DbUtils

    Ceremonial connection code

    String db = "jdbc:h2:mem:;INIT=runscript from 'classpath:/prototypeeop.sql'"; 
    //for H2 in-memory database:
    Connection DriverManager.getConnection(db);
    
    

    Remember the core classes and interfaces in Commons DbUtils are QueryRunner and ResultSetHandler.

    0 讨论(0)
  • 2020-12-15 02:41

    You can try MySQL JDBC Utilities API for MySQL connectivity.

    This API offers very cool features and also fulfill your requirement!

    0 讨论(0)
  • 2020-12-15 02:44

    Two ways you can make it

    1. Override determineCurrentLookupKey() method of Spring's AbstractRoutingDataSource class.

    2. You can create a class which will return Connection based on system.

    0 讨论(0)
提交回复
热议问题