JavaでMySQLを利用しています。

引数をデータベースの名前URLを設定し、接続するクラスが作りたいのですが、これが可能ならば、お手本を、お示しいただければ、幸いです。
今まで接続しているのは、下記のものです。
public class ConnectionManager {
final static String DRIVER="com.mysql.jdbc.Driver";
final static String URL="jdbc:mysql://localhost/ncode_oooo";
final static String USER="root";
final static String PASS="xxxxxx55";
public static Connection getConnection()
throws SQLException{
try{
Class.forName(DRIVER);
}catch (ClassNotFoundException e){
e.printStackTrace();
throw new IllegalStateException("fail to class load:"+e.getMessage());
}
Connection con=DriverManager.getConnection(URL,USER,PASS);
return con;
}

回答の条件
  • 1人2回まで
  • 登録:
  • 終了:2017/10/12 13:59:29
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

回答1件)

id:a-kuma3 No.1

回答回数4973ベストアンサー獲得回数2154

ポイント200pt

メソッドに引数をつけて、クラスの外からは、引数に URL などを指定して呼び出します。

public class ConnectionManager {
    final static String DRIVER="com.mysql.jdbc.Driver";
    public static Connection getConnection(String url, String user, String pass)
        throws SQLException{
        try{
            Class.forName(DRIVER);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            throw new IllegalStateException("fail to class load:"+e.getMessage());
        }
        Connection con=DriverManager.getConnection(url, user, pass);
        return con;
    }
}

呼ぶ側。

public class Test {
    public static void main(String[] args) {
        String u = "jdbc:mysql://localhost/ncode_oooo";
        String us = "root";
        String ps = "xxxxxx55";
        Connection con = ConnectionManager.getConnection(u, us, ps);
    }
}

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません