// 以下是加载驱动的三种方法
// Class.forName("oracle.jdbc.driver.OracleDriver");--------》常用
// new oracle.jdbc.driver.OracleDriver();
// System.setProperty("jdbc.drivers","oracle.jdbc.driver.OracleDriver");----------------》很少用
说出数据连接池的工作机制是什么?
J2EE服务器启动时会建立一定数量的池连接,并一直维持不少于此数目的池连接。客户端程序需要连接时,池驱动程序会返回一个未使用的池连接并将其表记为忙。如果当前没有空闲连接,池驱动程序就新建一定数量的连接,新建连接的数量由配置参数决定。当使用的池连接调用完成后,池驱动程序将此连接表记为空闲,其他调用就可以使用这个连接。
首先把使用数据库的驱动包准备好!
import java.sql.Connection; import java.sql.DriverManager; /** * 连接sqlserver2008r2 */ public class Connect { public static void main(String[] args) { Connection conn = null; try { String url = "jdbc:jtds:sqlserver://localhost:1401;databaseName=edmms-jjjt;user=sa;password=sasa"; Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager.getConnection(url); System.out.println("Database connection established"); } catch (Exception e) { System.err.println("Cannot connect to database server"); } finally { if (conn != null) { try { conn.close(); System.out.println("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * java连接postgreSQL数据库。 * */ public class TestDB { public TestDB() { } public static void main(String args[]) { try { Class.forName("org.postgresql.Driver").newInstance(); String url = "jdbc:postgresql://localhost:5432/mydb"; Connection con = DriverManager.getConnection(url, "postgres", "julong"); Statement st = con.createStatement(); //String sql = "select * from cities"; String sql = "insert into organization(sn,title,remark) values(22,'123','测试序号')"; ResultSet rs = st.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); } rs.close(); st.close(); con.close(); } catch (Exception ee) { System.out.print(ee.getMessage()); } } }
import java.sql.Connection; import java.sql.DriverManager; public class MySqlConnect { public static void main (String[] args) { Connection conn = null; try { String userName = "root"; String password = "root"; String url = "jdbc:mysql://localhost/test"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url, userName, password); System.out.println ("Database connection established"); } catch (Exception e) { System.err.println ("Cannot connect to database server"); } finally { if (conn != null) { try { conn.close (); System.out.println ("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } } }
Java中数据库驱动程序加载及建立连接