Java中使用JDBC连接oracle数据库

ConnectionFactory类:

package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
public class ConnectionFactory {
 
 private Connection connection = null; 
 private String url = "jdbc:oracle:thin:@localhost:1521:ORACLE";
 
 /**
  * 创建连接
  * @return
  */
 public Connection createConnection(){  
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   connection = DriverManager.getConnection(url, "scott", "tiger");
   return connection;   
  } catch (ClassNotFoundException e) {
   Logger.getLogger(this.getClass()).error(e.getMessage());
   return null;
  } catch (SQLException e) {
   Logger.getLogger(this.getClass()).error(e.getMessage());
   return null;
  }
 } 
 /**
  * 释放连接
  */
 public void releaseConnection(){  
  if (connection!=null)
   try {
    connection.close();
   } catch (SQLException e) {
    Logger.getLogger(this.getClass()).error(e.getMessage());
   }
 }
}

测试类:Test.java

package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {

 private static ConnectionFactory cFactory = new ConnectionFactory();
 static ResultSet rs = null;
 static Connection connection = null;
 static Statement statement = null;
 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
//   Statement statement = cFactory.createConnection().createStatement();   
//   ResultSet rs = statement.executeQuery("select * from test");
   /*上面注释掉的程序是之前写的,可是查询不出数据,rs.next()方法一直是false,后来百度后,使用PrepareStatement替代Statement,解决了问题*/
   PreparedStatement pState = cFactory.createConnection().prepareStatement("select * from test");
   ResultSet rs = pState.executeQuery();

   while(rs.next()){
       String id = rs.getString("id");
       String name = rs.getString("name");  //【等同写法:String name = rs.getString(2);此时name要对应数据库中的第二列】
       String age = rs.getString("age");
       String sex = rs.getString("sex");
       System.out.println("id="+id+";name="+name+";age="+age+";sex="+sex);

   }
  } catch (SQLException e) {
       e.printStackTrace();
  }  
 } 
}

你可能感兴趣的:(Java中使用JDBC连接oracle数据库)