1 package org.lans.test; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 import java.util.Properties; 9 10 public class JDBCConnect { 11 private static String url; 12 private static String username; 13 private static String password; 14 public static void getProps(){ 15 Properties props=new Properties(); 16 try { 17 props.load(JDBCConnect.class.getClassLoader().getResourceAsStream("jdbc.properties")); 18 /** 19 * mysql驱动类:com.mysql.jdbc.Driver 20 * mysql url:jdbc:mysql://localhost:3306/database 21 * oracle驱动类:oracle.jdbc.driver.OracleDriver 22 * oracle url:jdbc:oracle:thin:@localhost:1521:database 23 * DB2驱动类:com.ibm.db2.jdbc.app.DB2Driver 24 * db2 url:jdbc:db2://localhost:5000/sample 25 * sql server:net.sourceforge.jtds.jdbc.Driver 26 * sql server url:jdbc:jtds:sqlserver://localhost:port/database 27 */ 28 url=props.getProperty("connection.url"); 29 username=props.getProperty("connection.username"); 30 password=props.getProperty("connection.password"); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 } 35 /** 36 * 获取数据库连接 37 * @return conn 38 */ 39 public static Connection getConnection(){ 40 getProps(); 41 Connection conn=null; 42 try { 43 conn=DriverManager.getConnection(url,username,password); 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 return conn; 48 } 49 50 public static void close(Connection conn){ 51 if(conn!=null){ 52 try { 53 conn.close(); 54 } catch (SQLException e) { 55 e.printStackTrace(); 56 } 57 } 58 } 59 public static void close(Statement stmt){ 60 if(stmt!=null){ 61 try { 62 stmt.close(); 63 } catch (SQLException e) { 64 e.printStackTrace(); 65 } 66 } 67 } 68 public static void close(ResultSet rs){ 69 if(rs!=null){ 70 try { 71 rs.close(); 72 } catch (SQLException e) { 73 e.printStackTrace(); 74 } 75 } 76 } 77 }