人力検索はてな
モバイル版を表示しています。PC版はこちら
i-mobile

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;
}

●質問者: kojiro_i619
●カテゴリ:ウェブ制作
○ 状態 :終了
└ 回答数 : 1/1件

▽最新の回答へ

1 ● a-kuma3
●200ポイント

メソッドに引数をつけて、クラスの外からは、引数に 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);
 }
}
関連質問

●質問をもっと探す●



0.人力検索はてなトップ
8.このページを友達に紹介
9.このページの先頭へ
対応機種一覧
お問い合わせ
ヘルプ/お知らせ
ログイン
無料ユーザー登録
はてなトップ