1. 程式人生 > >重溫資料庫操作JDBC

重溫資料庫操作JDBC

前言

    	在日常的開發當中,我們總是用框架去連線資料庫,去完成業務中的需求,但是不可避免的有時候我們需要對資料進行額外的處理, 
    批量的修改或查詢,這時候用框架就顯得有點殺雞用牛刀了,在這裡我們將重溫原始的JDBC操作,好記性不如爛筆頭。

JDBC操作步驟

    1.註冊驅動
    2.獲取連線
    3.執行預處理語句
    4.新增佔位符
    5.結果遍歷或者查詢修改記錄條數
    6.釋放資源

程式碼

    1.匯入資料庫連線需要的jar包,這裡使用maven
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    2.增刪改查的測試
        import org.junit.Test;

        import java.sql.*;

        public class DBTest {

            /**
            * 增
            *
            * @throws ClassNotFoundException
            * @throws SQLException
            */
            @Test
            public void test01() throws ClassNotFoundException, SQLException {
                //1.註冊驅動
                Class.forName("com.mysql.jdbc.Driver");
                //2.獲取連線
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "asdfmin");
                //3.獲得預處理語句
                String sql = "insert into user (name, sex, age) values (? , ?, ?)";
                PreparedStatement preparedStatement = conn.prepareStatement(sql);
                //4.新增佔位符
                preparedStatement.setString(1, "jack");
                preparedStatement.setString(2, "男");
                preparedStatement.setString(3, "18");
                //5.執行預處理語句
                int i = preparedStatement.executeUpdate();
                System.out.println("新增新記錄條數:" + i);
                //6.釋放資源
                preparedStatement.close();
                conn.close();
            }

            /**
            * 更
            *
            * @throws ClassNotFoundException
            * @throws SQLException
            */
            @Test
            public void test02() throws ClassNotFoundException, SQLException {
                //1.註冊驅動
                Class.forName("com.mysql.jdbc.Driver");
                //2.獲取連線
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "asdfmin");
                //3.獲取預處理語句
                String sql = "update user set age = ? where name = ?";
                PreparedStatement preparedStatement = conn.prepareStatement(sql);
                //4.新增佔位符
                preparedStatement.setString(1, "19");
                preparedStatement.setString(2, "jack");
                //5.執行預處理語句
                int i = preparedStatement.executeUpdate();
                System.out.println("更新記錄條數:" + i);
                //6.釋放資源
                preparedStatement.close();
                conn.close();
            }

            /**
            * 刪
            *
            * @throws ClassNotFoundException
            * @throws SQLException
            */
            @Test
            public void test03() throws ClassNotFoundException, SQLException {
                //1.註冊驅動
                Class.forName("com.mysql.jdbc.Driver");
                //2.獲取連線
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "asdfmin");
                //3.獲取預處理語句
                String sql = "delete from user where id = ?";
                PreparedStatement preparedStatement = conn.prepareStatement(sql);
                //4.新增佔位符
                preparedStatement.setString(1, "1");
                //5.執行預處理
                int i = preparedStatement.executeUpdate();
                System.out.println("刪除記錄條數:" + i);
                //6.釋放資源
                preparedStatement.close();
                conn.close();
            }

            /**
            * 查
            * @throws ClassNotFoundException
            * @throws SQLException
            */
            @Test
            public void test04() throws ClassNotFoundException, SQLException {
                //1.註冊驅動
                Class.forName("com.mysql.jdbc.Driver");
                //2.獲取連線
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "asdfmin");
                //3.獲取預處理語句
                //String sql = "select * from user";
                String sql = "select * from user where name = ?";
                PreparedStatement preparedStatement = conn.prepareStatement(sql);
                //4.新增站位符
                preparedStatement.setString(1, "jack");
                //5.執行預處理
                ResultSet resultSet = preparedStatement.executeQuery();
                //6.遍歷結果集
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    String sex = resultSet.getString("sex");
                    String age = resultSet.getString("age");
                    System.out.println("id:" + id + "   name:" + name + "  set:" + sex + "  age:" + age);
                }
                //7.關閉資源
                resultSet.close();
                preparedStatement.close();
                conn.close();
            }

        }

    3.說明
    這裡用的是預處理語句PreparedStatement(防止sql注入攻擊)

對於JDBC的簡單封裝

    對於頻繁的註冊驅動獲取連線我們可以進行簡單的封裝
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.SQLException;

        public class JDBCUtils {

            private static final String DRIVERNAME = "com.mysql.jdbc.Driver";
            private static final String URL = "jdbc:mysql://localhost:3306/test";
            private static final String USER = "root";
            private static final String PASSWORD = "asdfmin";

            static {
                try {
                    //1.註冊驅動
                    Class.forName(DRIVERNAME);
                } catch (ClassNotFoundException e) {
                    System.out.println("註冊驅動失敗");
                    e.printStackTrace();
                }
            }

            public static Connection getConn() throws SQLException {
                //2.獲取連線
                Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
                //返回連線
                return conn;
            }

        }

測試封裝的JDBC工具類

        import org.junit.Test;

        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;

        public class DBUtilTest {

            /**
            * 測試封裝的JDBCUtil
            */
            @Test
            public void test01() {
                Connection conn = null;
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {
                    //1.獲取連線
                    conn = JDBCUtils.getConn();
                    //2.獲取執行語句
                    String sql = "select * from user";
                    preparedStatement = conn.prepareStatement(sql);
                    //3.新增佔位符
                    //4.執行預處理語句
                    resultSet = preparedStatement.executeQuery();
                    //5.遍歷結果集
                    while (resultSet.next()) {
                        String name = resultSet.getString("name");
                        System.out.println("name:" + name);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    //6.釋放資源
                    try {
                        resultSet.close();
                        preparedStatement.close();
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

API的一些簡單說明

    執行預處理語句的API
    int executeUpdate(); --執行insert update delete語句.
    ResultSet executeQuery(); --執行select語句.
    boolean execute(); --執行select返回true 執行其他的語句返回false.

後記

    溫故而知新。