JDBCUtils——原生

Posted Xin.Wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBCUtils——原生相关的知识,希望对你有一定的参考价值。

需要导入的包:

  • mysql-connector-java-5.1.37-bin.jar

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
    导包:
        mysql-connector-java-5.1.37-bin.jar
*/
public class JdbcUtils {
    private static String DRIVER = "com.mysql.jdbc.Driver";
    private static String URL = "jdbc:mysql://localhost:3306/newdatabase";
    private static String USER = "root";
    private static String PASSWORD = "1234";

    static {
        try {
            Class.forName(DRIVER);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得连接
     * 
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        return connection;
    }

    /**
     * 释放资源
     * 
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void closeResouce(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {

            try {
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

 

以上是关于JDBCUtils——原生的主要内容,如果未能解决你的问题,请参考以下文章

JdbcUtils工具类代码

JdbcUtils工具类代码

JDBC3.工具类-JDBCUtils

JDBCUtils

工具类JdbcUtils

JavaWeb基础之JdbcUtils工具类2.0