本文共 2212 字,大约阅读时间需要 7 分钟。
1、工具类的设计,设计成final,不被继承
package cn.itcast.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * Jdbc工具类 */public final class JdbcUtils { //省略localhost:3306 private static String url = "jdbc:mysql:///jdbc"; private static String username = "root"; private static String password = "root"; /** * 构造器私用,防止直接创建对象, * 当然通过反射可以创建 */ private JdbcUtils(){ } //保证只是注册一次驱动 static{ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } /** * 获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } /** * 释放资源 */ public static void free(ResultSet rs, Statement st, Connection conn) { //规范的关系连接的方式 try{ if(rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ try{ if(st != null) { st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally { if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }}
2、主类中的代码
package cn.itcast.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * 第一个JDBC程序 */public class Base { public static void main(String[] args) throws SQLException, ClassNotFoundException { template(); } /** * 比较严谨的实现方式 * @throws ClassNotFoundException * @throws SQLException */ public static void template() throws ClassNotFoundException, SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; try { //建立连接 conn = JdbcUtils.getConnection(); //创建语句 st = conn.createStatement(); //执行语句 rs = st.executeQuery("select * from user"); //处理结果集 while(rs.next()) { System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" + rs.getObject(3) + "\t" + rs.getObject(4)); } } finally { JdbcUtils.free(rs, st, conn); } }}运行结果:
1 zhangsan 2017-06-30 100.0
2 lisi 2017-06-06 200.0
3 wangwu 2017-05-30 300.0
转载地址:http://uklvb.baihongyu.com/