JDBC工具类

有增删改查数据库的功能

使用时只需要改一下对应的数据库用户名,数据库密码,数据库名字,服务器IP地址即可。一次编程终身受益。

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库连接工具类
 * @author Administrator
 *
 */
public class JDBCUtil {
    private static final String DB_USER_NAME="root";//数据库用户名
    private static final String DB_PASSWORD="root";//数据库密码
    private static final String DB_NAME="user_management";//数据库名称
    private static final String IP="127.0.0.1";//服务器IP地址
    private static final String URL="jdbc:mysql://"+IP+":3306/"+DB_NAME;//mysql连接
    
    private static Connection conn;//创建连接对象(路)
    private static Statement stmt;//执行命令的对象(执行sql语句)(人)
    private static ResultSet rs;//保存select之后查询结果的数据的对象(车)
    
    /**
     * 获取数据库连接对象Connection
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private static Connection getCon() throws ClassNotFoundException, SQLException{
        //加载MySql驱动
        Class.forName("com.mysql.jdbc.Driver");
        if(conn==null||conn.isClosed()){
            conn=DriverManager.getConnection(URL, DB_USER_NAME, DB_PASSWORD);
        }
        return conn;//java单例模式可以让代码更优秀
    }
    
    /**
     * 获得statement对象用于执行Sql语句
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private static Statement openStmt() throws ClassNotFoundException, SQLException{
        stmt=getCon().createStatement();
        return stmt;
    }
    
    
    /**
     * 执行数据库的增(insert),删(delete),改(update)操作
     * @param sql
     * @return
     */
    public static int executeSQL(String sql){
        int i=0;
        try {
            i=openStmt().executeUpdate(sql);//执行sql语句
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭数据库相关对象
            close();
            
        }
        
        return i;
    }
    
    
    /**
     * 执行数据库查询(select)的操作
     * @param sql
     * @return
     */
    public static ResultSet search(String sql){
        try {
            rs=openStmt().executeQuery(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    
    
    /**
     * 关闭数据库的方法
     */
    public static void close(){
        //先关车,再关人,最后关路
        try {
            if(rs!=null)
                rs.close();//关闭ResultSet(车)
            if(stmt!=null)
                stmt.close();//关闭Statement对象(人)
            if(conn!=null)
                conn.close();//关闭Connection对象(路)
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
}
原文地址:https://www.cnblogs.com/lumc5/p/15249922.html