JavaWeb 使用 Druid 連接池查詢數據庫

Maven 配置

本 Demo 使用 Maven 創建,如果你沒有使用該工具也無傷大雅,自己下載對應的 jar 包放到 lib目錄下就可以了。

這裏是 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>top.wsuo</groupId>
    <artifactId>jdbc-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>jdbc-demo Maven Webapp</name>


    <dependencies>
        <!--Junit 單元測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!--mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
            <scope>compile</scope>
        </dependency>

        <!--Druid 數據庫連接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>jdbc-demo</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <!--maven插件-->
        <plugins>
            <!--jdk編譯插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <!--tomcat插件-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <!-- tomcat7的插件, 不同tomcat版本這個也不一樣 -->
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <!-- 通過maven tomcat7:run運行項目時,訪問項目的端口號 -->
                    <port>8080</port>
                    <!-- 項目訪問路徑  本例:localhost:9090,  如果配置的aa, 則訪問路徑爲localhost:9090/aa-->
                    <path>/</path>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

創建工具類

創建數據庫連接池的工具類,負責創建連接對象。

public class JdbcUtil {

    private static DataSource dataSource;

    // 註冊驅動
    static {
        try {
            InputStream resource = Druid
                    .class
                    .getClassLoader()
                    .getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(resource);
            dataSource = DruidDataSourceFactory
                    .createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnect() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void close(Connection conn,
                             PreparedStatement statement) {
        assert conn != null;
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        assert statement != null;
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn,
                             PreparedStatement statement,
                             ResultSet resultSet) {

        close(conn, statement);
        assert resultSet != null;
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

配置文件

Druid 是通過讀取配置文件的方式加載類,所以我們必須提供配置文件,默認要放在 classpath 路徑下,在我們的 web' 項目中就是 resource 目錄,前提你要把該目錄標記爲 resource 資源文件夾:
在這裏插入圖片描述
標記方法:

右鍵文件夾,選擇 mark
在這裏插入圖片描述

配置文件內容如下:

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql:///school?characterEncoding=utf-8
username = root
password = root
initialSize=5
maxActive=10
maxWait=3000

CRUD

實體類:

public class Student {
    private int id;
    private String name;
    private int age;
    private String qq;

    public Student(int id) {
        this.id = id;
    }

    public Student(String name, int age, String qq) {
        this.name = name;
        this.age = age;
        this.qq = qq;
    }

    public Student(int id, String name, int age, String qq) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.qq = qq;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", qq='" + qq + '\'' +
                '}';
    }
}

CRUD 類:

public static List<Student> queryAll(Connection connection) throws SQLException {
        String sql = "select * from school.student;";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        List<Student> list = new ArrayList<>();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            String qq = resultSet.getString("qq");
            list.add(new Student(id, name, age, qq));
        }
        return list;
    }

    public static int insert(Connection connection, Student student) throws SQLException {
        String sql = "insert into school.student(name, age, qq) values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, student.getName());
        statement.setInt(2, student.getAge());
        statement.setString(3, student.getQq());
        int i = statement.executeUpdate();
        Druid.close(connection, statement);
        return i;
    }

    public static int update(Connection connection, Student student) throws SQLException {
        String sql = "UPDATE school.student SET NAME = ? WHERE id = ?";
        assert connection != null;
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, student.getName());
        statement.setInt(2, student.getId());
        return statement.executeUpdate();
    }

    public static int delete(Connection connection, int id) throws SQLException {
        String sql = "delete from school.student WHERE id = ?";
        assert connection != null;
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        return statement.executeUpdate();
    }

// 測試方法
	public static void main(String[] args) throws SQLException {
        Connection connection = JdbcUtil .getConnect();
        assert connection != null;
        int n1 = delete(connection, 2);
        System.out.println(n1);
        int n2 = insert(connection,
                new Student("劉能", 23, "34123413"));
        System.out.println(n2);
        List<Student> list = queryAll(connection);
        for (Student student : list) {
            System.out.println(student);
        }
	}

其中 Student 是我們封裝的實體類。

Web.xml 配置 Druid 監控

如果我們想監控數據庫怎麼辦呢 ?

也很簡單,Druid 已經爲我們封裝好了一個類,我們可以直接請求,只需要在配置文件中配置一下訪問路徑和初始化參數…

來看 web.xml

	<!-- 配置 Druid 監控信息顯示頁面 -->
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        <init-param>
            <!-- 允許清空統計數據 -->
            <param-name>resetEnable</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <!-- 用戶名 -->
            <param-name>loginUsername</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <!-- 密碼 -->
            <param-name>loginPassword</param-name>
            <param-value>root</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

然後訪問 http://localhost:8080/druid/login.html就可以看到這樣一個頁面:
在這裏插入圖片描述
輸入我們在 web.xml 中配置的用戶名和密碼即可登錄

在這裏插入圖片描述
至於爲什麼可以看到這些頁面,其實都是 Druid 幫我們封裝好了。

來看 jar 包,發現這裏面就有一個 web 項目,我們可以直接訪問。
在這裏插入圖片描述
Alibaba 太強了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章