这JAVA JDBC对象是什么意思
接口:
package db;
import java.sql.Connection;
import
java.sql.SQLException;
public interface DBSource {
public Connection getConnection() throws
SQLException;
public void closeConnection(Connection conn) throws SQLException;
}
接口实现类:
package db;
import java.io.FileInputStream;
import
java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class SimpleDBSource implements DBSource {
private Properties props;
private String url;
private String user;
private String password;
public SimpleDBSource() throws
IOException,
ClassNotFoundException{
this("jdbc.properties");
}
public SimpleDBSource(String configFile) throws IOException,Class
NotFoundException{
props = new Properties();
props.load(new FileInputStream(configFile));
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
Class.forName(props.getProperty("driver"));
}
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,user,password);
}
public void closeConnection(Connection conn) throws SQLException{
conn.close();
}
}
测试类:
package db;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionDemo {
public static void main(String args[]){
try{
DBSource dbSource = new SimpleDBSource();
Connection conn = dbSource.getConnection();
if(!conn.isClosed()){
System.out.println("数据库已连接上");
}
dbSource.closeConnection(conn);
if(conn.isClosed()){
System.out.println("");
}
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
}
}
这是书上的一个例子,有点不太明白,各位大哥,想问一下上面这个测试类中的DBSource dbSource = new SimpleDBSource();Connection conn = dbSource.getConnection();这两个是什么意思,我一直看不明白,能否详细解释一下啊,还有为什么要这样声明对象的,
------解决方案--------------------
上面这个测试类中的DBSource dbSource = new SimpleDBSource();Connection conn = dbSource.getConnection();
因为 SimpleDBSource 实现 DBSource接口 ,所以 SimpleDBSource的实例可以赋值给 DBSource接口的引用 ,dbSource.getConnection();--java虚拟机 会自动匹配具体是那个实现类的getConnection方法