JDBC
JDBC是JDK提供的JAVA访问关系型数据库的SPI,有多种实现方式。
ODBC是微软提出的!O是open不是oracle。也是最造被开发者和数据库厂商接收的交互方案。所以可以在ODBC的基础上构建JDBC,称为JDBC-ODBC Bridge Driver。ODBC通过调用数据库的本地客户端的API和远程数据库通信交互。
当然,可以直接调用数据库本地的客户端。也就是Native API Driver。不过,JDBC实现者就无法做到硬件无关了。所以,不被推荐。
JDBC-Net Driver,Java将sql翻译为数据库无关的操作协议,发给中间服务器,中间服务器负责翻译为具体服务器的操作转发到数据库服务器。ADO.NET是使用这种方案的。
Native Protocol Driver 最常用的一种,JDBC实现者直接将命令转化为操作数据的网络请求,直接发送给数据库。mysql-connector-java就属于这一种。
JDBC对数据库操作基本如下
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
//建立连接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//执行SQL
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//分析结果
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
}
JNDI
JNDI可以配置在诸如Tomcat这样的容器中。提供程序员数据访问,而开发者不需要在代码里关系数据访问的细节。以tomcat为例,server.xml配置文件如下,配置两个数据源
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<Resource auth="Container"
description="DB Connection"
driverClass="oracle.jdbc.driver.OracleDriver"
maxPoolSize="20"
minPoolSize="5"
acquireIncrement="5"
maxIdleTime="300"
idleConnectionTestPeriod="60"
automaticTestTable="Test"
acquireRetryAttempts="30"
breakAfterAcquireFailure="true"
name="jdbc/amodMonDbSource"
user="amod"
password="amoddb"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:oracle:thin:@10.111.0.108:1521:orcl" />
<Resource auth="Container"
description="DB Connection"
driverClass="oracle.jdbc.driver.OracleDriver"
maxPoolSize="20"
minPoolSize="5"
acquireIncrement="5"
maxIdleTime="300"
idleConnectionTestPeriod="60"
automaticTestTable="Test"
acquireRetryAttempts="30"
breakAfterAcquireFailure="true"
name="jdbc/ddamodMonDbSource"
user="ddamod"
password="ddamoddb"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:oracle:thin:@10.111.0.108:1521:orcl" />
</GlobalNamingResources>
然后还需要在context.xml中进行配置
<!-- The contents of this file will be loaded for each web application -->
<Context>
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<ResourceLink name="jdbc/amodMonDbSource" global="jdbc/amodMonDbSource" type="javax.sql.DataSource"/>
<ResourceLink name="jdbc/ddamodMonDbSource" global="jdbc/ddamodMonDbSource" type="javax.sql.DataSource"/>
</Context>
最后就是实际使用了
Connection conn=null;try {
Context ctx=new InitialContext();
Object datasourceRef=ctx.lookup("java:MySqlDS");
......
c.close();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(conn!=null) {
try {
conn.close();
} catch(SQLException e) { }
}
}