大神帮帮忙,java怎样连接数据库?在线等急急急!
java怎样连接数据库?
java怎样连接数据库?
2015-12-15
个人研究用: 0.去oracle安装目录找一个名为class12.jar的jar包,放到项目的lib里 1.在META-INF 建立个context.xml文件 <?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/crm" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:oracle" username="crm" password="crm" maxActive="4" maxIdle="2" maxWait="3000"/> </Context> 2. //数据库链接池 第一个类 用来链接数据库 package com.baidu.crm.common; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.omg.CORBA.Request; //连接池 public class DataSourceManager { public static Connection getConnection(){ DataSource ds=null; try { Context context=new InitialContext(); ds=(DataSource)context.lookup("java:comp/env/jdbc/crm");//crm数据库名 } catch (NamingException e) { e.printStackTrace(); } Connection con=null; try { con=ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return con; } public static void closeDBSource(ResultSet rs,Statement st,Connection con){ try { if(rs!=null){ rs.close(); } if(st!=null){ st.close(); } if(con!=null){ con.close(); } } catch (SQLException e) { e.printStackTrace(); } } } 3.//调用链接的类 package com.baidu.crm.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.baidu.crm.common.DataSourceManager; import com.baidu.crm.entity.City; public class CityDao { public List<City> getCityList() { List<City> result=new ArrayList<City>(); Connection con=null; PreparedStatement ps=null; ResultSet rs=null; con=DataSourceManager.getConnection(); try { ps=con.prepareStatement("select city_code,city_name from city"); rs=ps.executeQuery(); while(rs.next()){ City city=new City(); city.setCityCode(rs.getInt("city_code")); city.setCityName(rs.getString("city_name")); result.add(city); } } catch (SQLException e) { e.printStackTrace(); }finally{ DataSourceManager.closeDBSource(rs, ps, con); } return result; } }
举报