JDBC

2019-04-19  本文已影响0人  hgzzz

JDBC

  1. 导入对于数据库的jar包,比如使用MySQL,就导入它的包。
  2. 编写代码
public class MainDemo {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try {
            // 1. 注册驱动
            // DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 这样会注册两次驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 建立连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/hgzdata", "root", "root");
            // 3. 创建statement
            statement = conn.createStatement();
            // 4. 新建查询语句
            String sql = "select * from product";
            // 5. 查询数据 得到结果集
            rs = statement.executeQuery(sql);
            // 6. 处理数据
            while(rs.next()) {
                int id = rs.getInt("pid");
                String pname = rs.getString("pname");
                Double price = rs.getDouble("price");
                System.out.println("id =" + id + "; name = " + pname + "; price = " + price);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 释放资源
            JDBCUtil.release(conn,statement,rs);
        }
    }
}
  1. 应用,使用JUnit来测试代码
public class JDBCUtil {

    static String driverClass = null;
    static String url = null;
    static String user = null;
    static String password = null;

    static { // 在类初始化时读取配置属性
        try {
        // 创建一个属性配置对象
        Properties properties = new Properties();
        // 获取文件的字节输入流
        // InputStream is = new FileInputStream("jdbc.properties"); // 文件输入流,文件放在工程根目录下
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); // 在加载类字节文件时加载通目录下的资源文件
        properties.load(is);
        // 读取属性
        driverClass = properties.getProperty("driverClass");
        url = properties.getProperty("url");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接数据库
     * @return
     */
    public static Connection getConn() {
        Connection conn = null;
        // 1. 注册驱动
        // DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 这样会注册两次驱动
        try {
            Class.forName(driverClass);
            // 2. 建立连接
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }

    /**
     * 释放资源
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn, Statement st, ResultSet rs) {
        closeRs(rs);
        closeConnection(conn);
        closeStatement(st);
    }

    private static void closeRs(ResultSet rs) {
        try {
            if (rs != null){
                rs.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs = null;
        }
    }

    private static void closeStatement(Statement st) {
        try {
            if (st != null){
                st.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            st = null;
        }
    }

    private static void closeConnection(Connection conn) {
        try {
            if (conn != null){
                conn.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
        }
    }
}
@Test
puclic void testQuery() {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 获取连接对象
            conn = JDBCUtil.getConn();
            // 2. 根据连接对象得到statement
            statement = conn.createStatement();
            String sql = "select * from product";
            // 3. 执行sql语句放回数据
            resultSet = statement.executeQuery(sql);
            // 4. 处理数据
            while(resultSet.next()) {
                System.out.println(resultSet.getInt("pid") + resultSet.getString("pname"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(conn, statement, resultSet);
        }
    }
}
 public void testInsert() {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 获取连接对象
            conn = JDBCUtil.getConn();
            // 2. 根据连接对象得到statement
            statement = conn.createStatement();
            // 3. 执行添加操作
            String sql = "insert into product values(null, 'iPhone X', 8888, 1 )";
            int result = statement.executeUpdate(sql);
            if (result > 0) {
                System.out.println("插入成功");
            } else {
                System.out.println("插入失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(conn, statement);
        }
    }
  1. Dao(Date Access Object)模式
  1. statement的安全问题
// 替换第二步的创建statement 对象
String sql = "select * from user where username=? and password=?";
PreparedStatement ps = conn.preparedStatement(sql);
ps.setString(1, username);
ps.setString(2, password)
上一篇下一篇

猜你喜欢

热点阅读