Java连接数据库

来源:互联网 发布:mac war3 不能局域网 编辑:程序博客网 时间:2024/06/03 23:46
 

package com.icss.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.icss.vo.TestVO;

public class TestConnection {

 /**
  * @param args
  */
 static Connection conn  = null;
 public static Connection getConn(){
  
  //1.注册驱动
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   try {
    conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","19890405");
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
    
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  return conn;
 }
 
 public static void closeConn(){

   if(conn!=null){
    try {
     conn.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   } 
 }
 
 public int addObject(int id,String name){
    Statement  st = null;
    ResultSet rs = null;
    int i=0;
    Connection conn = getConn();
     try {
     st = conn.createStatement();
     i  = st.executeUpdate("insert into test values("+id+",'"+name+"')");
      System.out.println(i);
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }finally{
     
     closeConn();
    }
    return i;
 
 }
 
 public List findObject(){
  Statement  st = null;
  ResultSet rs = null;
  
  ArrayList li = new ArrayList();
  TestVO vo = null;
  int i=0;
  Connection conn = getConn();
   try {
   st = conn.createStatement();
    rs = st.executeQuery("select * from test");
    while(rs.next()){
     vo = new TestVO();
    
     vo.setId(rs.getInt(1));
     vo.setName(rs.getString("name"));
    
     li.add(vo);
    }
    System.out.println(i);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   
   closeConn();
  }
  return li;

}
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  TestConnection  tc = new TestConnection();
  
  List list = tc.findObject();
  Iterator it = list.iterator();
  while(it.hasNext()){
   
   TestVO vo = (TestVO)it.next();
   System.out.println(vo.getId()+vo.getName());
   
  }
  
  tc.addObject(55, "erw");
  
  List list1 = tc.findObject();
  Iterator it1 = list1.iterator();
  while(it1.hasNext()){
   
   TestVO vo = (TestVO)it1.next();
   System.out.println(vo.getId()+vo.getName());
   
  }
  
  
 }
}