BeanFactory.java
package two;
public class BeanFactory {
public JDBCInter createBean(String dbname){
JDBCInter jdbc = null;
if("sql".equals(dbname)){
return new MySQLJDBC();
}else if("mysql".equals(dbname)){
return new SqlJDBC();
}
return null;
}
}
BeanFactory01.java
package two;
public class BeanFactory01 {
public JDBCInter createBean(String dbname){
JDBCInter jdbc = null;
try {
jdbc = (JDBCInter)Class.forName(dbname).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jdbc;
}
}
JDBCInter.java
package two;
import java.sql.Connection;
public interface JDBCInter {
public Connection getConn();
}
MySQLJDBC.java
package two;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLJDBC implements JDBCInter {
String url = "jdbc:mysql://127.0.0.1:3306";
String username="root";
String password="root";
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Connection getConn() {
// TODO Auto-generated method stub
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
SqlJDBC.java
package two;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SqlJDBC implements JDBCInter {
String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=";
String username="sa";
String password="123";
static{
try {
Class.forName("com.mysql.jdbc.sqlserver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Connection getConn() {
// TODO Auto-generated method stub
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Main.java