WebのJDBC接続
1649 ワード
/*
* Connection
* 1.
* 2.
* 3. Connection
*/
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/ea";
String username = "root";
String password = "root";
//
Class.forName(driverClassName);
// DriverManager, 3 , Connection
Connection con = DriverManager.getConnection(url, username, password);
ステップアップ
JdbcUtils.java
public class JdbcUtils {
private static Properties props = null;
// JdbcUtils !
static {
// props , dbconfig.properties props
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
props = new Properties();
props.load(in);
} catch(IOException e) {
throw new RuntimeException(e);
}
//
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// !
public static Connection getConnection() throws SQLException {
// Connection
return DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
}
}
使用
@Test
public void fun1() throws SQLException {
Connection con = JdbcUtils.getConnection();
System.out.println(con);
Connection con1 = JdbcUtils.getConnection();
System.out.println(con1);
}