日期:2014-05-20 浏览次数:20786 次
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Conn { public Connection conn = null; public Statement stmt = null; public ResultSet rs = null; private static String dbClassName ="oracle.jdbc.driver.OracleDriver"; private static String dbUrl ="dbc:oracle:thin:@127.0.0.1:1521:jzmorcl"; private static String user = "scott"; private static String password ="tiger"; public static Connection getConnection() { Connection conn = null; try { Class.forName(dbClassName).newInstance(); conn = DriverManager.getConnection(dbUrl,user,password); } catch (Exception ee) { ee.printStackTrace(); } if (conn == null) { System.err.println(); } return conn; } /** * 功能:执行查询语句 */ public ResultSet executeQuery(String sql) { try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); return rs; } catch (SQLException ex){ ex.printStackTrace(); return null; } } /** * 功能:执行更新操作 */ public int executeUpdate(String sql) { int result = -1; try { conn = getConnection(); //调用getConnection()方法构造Connection对象的一个实例conn //stmt = conn.createStatement(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); result = stmt.executeUpdate(sql); //执行更新操作 } catch (SQLException ex) { ex.printStackTrace(); return -1 ; }finally{ this.close(); } return result; } /** * 功能:关闭数据库的连接 */ public void close() { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(System.err); } } }