In Java, how do I set a return type if an exception occurs?

后端 未结 6 1062
[愿得一人]
[愿得一人] 2021-02-14 10:37

hey all, I\'m new to Java and was wondering if I define a method to return a database object

like

import java.sql.*;

public class DbConn {

    public          


        
6条回答
  •  一向
    一向 (楼主)
    2021-02-14 11:17

    I'm sorry, but you shouldn't be writing code like this, even if you're new to Java.

    If you must write such a thing, I'd make it more like this:

    public class DatabaseUtils 
    {
    
        public static Connection getConnection(String driver, String url, String username, String password) throws SQLException 
        {
            Class.forName(driver).newInstance();
    
    
            return DriverManager.getConnection(url, username, password);
        }
    }
    

    And you should also be aware that connection pools are the true way to go for anything other than a simple, single threaded application.

提交回复
热议问题