JDBC实现数据库操作总结
最近经常涉及到一些数据库的操作,总结了一些常用的数据库操作方法。
一、建立连接
JDBC(Java Data Base Connectivity)是Java中执行sql的一套api, 可以为多种数据库提供访问。建立数据库连接,执行sql语句等操作。
建立数据库链接:
/** * get db connection * @return */ public static Connection getConnection(){ Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, NAME, PASSWORD); logger.info("connection success"); } catch(SQLException ex) { logger.error("desc=get database connection error"); } catch (ClassNotFoundException e) { logger.error("desc=ClassNotFoundException error"); } return conn; }
二、执行sql语句
1、无返回结果:
/** * execute sql * @param sql sql语句 * @throws Exception */ public static void executesql(String sql) throws Exception{ Statement ps = null; Connection conn = getConnection(); try { if(conn != null) { ps = conn.createStatement(); ps.execute(sql); } } catch (SQLException e) { logger.error("desc=execute sql error"); } finally { if(conn != null) { try { conn.close(); } catch (Exception e) { logger.error("desc=close db connection error"); } } } }
2、影响行数
如果需要返回影响的行数,可以用executeUpdate():
Integer affectRows = ps.executeUpdate(sql);
3、返回查询的结果
ResultSet rs = ps.executeQuery(sql);
三、批量执行
/** * execute batch sqls * @param sqls * @throws Exception */ public static void batchexecutesql(List<String> sqls) throws Exception { Statement stat = null; Connection conn= getConnection(); try { if (conn != null) { stat = conn.createStatement(); for(String sqlStr:sqls) { stat.addBatch(sqlStr); } stat.executeBatch(); stat.close(); } } catch (SQLException e) { logger.error("desc=execute batch sqls error"); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { logger.error("desc=close db connection error"); } } } }
在上面的例子中,用的是CreateStatement()。 在实际开发中,一般都会用prepareStatement,CreateStatement 和 PrepareStatement 的区别主要有:
1)prepareStatement会初始化sql, 先把sql提交到数据库中进行预处理,多次使用时,可以提高效率;
2)prepareStatement可以替换sql中的变量,可以包含“?”。对于执行批量数据比较方便。
String sql = "delete from user where uid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1,uid); pstmt.executeUpdate();
3)安全上, 减少sql注入的机会。
在实际的应用中,根据性能等因素上选择合适的使用方式。