001package org.itsallcode.jdbc; 002 003import java.sql.*; 004import java.util.Properties; 005 006/** 007 * This class connects to a database using {@link DriverManager} and returns new 008 * {@link SimpleConnection}s. 009 * <p> 010 * Create a new instance using {@link #create()}. 011 */ 012public final class ConnectionFactory { 013 private final Context context; 014 private final DbDialectFactory dialectFactory; 015 016 private ConnectionFactory(final Context context, final DbDialectFactory dialectFactory) { 017 this.context = context; 018 this.dialectFactory = dialectFactory; 019 } 020 021 /** 022 * Create a new connection factory. 023 * 024 * @return a new instance 025 */ 026 public static ConnectionFactory create() { 027 return create(Context.builder().build()); 028 } 029 030 /** 031 * Create a new connection factory with a custom context. 032 * 033 * @param context a custom context 034 * @return a new instance 035 */ 036 public static ConnectionFactory create(final Context context) { 037 return new ConnectionFactory(context, new DbDialectFactory()); 038 } 039 040 /** 041 * Create a connection using the given JDBC URL. 042 * 043 * @param url JDBC URL 044 * @return a new connection 045 */ 046 public SimpleConnection create(final String url) { 047 return create(url, new Properties()); 048 } 049 050 /** 051 * Create a connection using the given JDBC URL. 052 * 053 * @param url JDBC URL 054 * @param user database user 055 * @param password database password 056 * @return a new connection 057 */ 058 public SimpleConnection create(final String url, final String user, final String password) { 059 final Properties info = new Properties(); 060 info.put("user", user); 061 info.put("password", password); 062 return create(url, info); 063 } 064 065 /** 066 * Create a connection using the given JDBC URL. 067 * 068 * @param url JDBC URL 069 * @param info connection properties 070 * @return a new connection 071 */ 072 public SimpleConnection create(final String url, final Properties info) { 073 return new SimpleConnection(createConnection(url, info), context, dialectFactory.createDialect(url)); 074 } 075 076 private static Connection createConnection(final String url, final Properties info) { 077 try { 078 return DriverManager.getConnection(url, info); 079 } catch (final SQLException e) { 080 throw new UncheckedSQLException("Error connecting to '" + url + "'", e); 081 } 082 } 083}