日期:2014-05-16  浏览次数:20555 次

JDBC编程步骤
具体代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestJDBC {

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@172.16.45.46:1521:orcl",USER,TIGER);
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while(rs.next()){
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
System.out.println(rs.getFloat("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs!=null)
{
rs.close();
rs=null;
}
if(stmt!=null)
{
stmt.close();
stmt=null;
}
if(conn!=null)
{
conn.close();
conn=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


如果业务复杂,则每一个与数据库交互的操作中都需要关闭掉所占用的资源。为了减少冗余,需要编写一个专门关闭相关链接的工具类。