mysql ----BaseDao工具类

package com.zjw.dao;

import java.sql.*;

/**
 * 工具类
 */
public class BaseDao {
    static final String DB_URL = "jdbc:mysql://localhost:3306/数据库";
    static final String username = "用户名";
    static final String paw = "密码";


    protected Connection conn;
    protected ResultSet rs;
    protected PreparedStatement ps;

    /**
     * 数据库的连接
     *
     * @return
     */
    public void connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, username, paw);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    /**
     * 增删改
     */
    public int executeUpdate(String sql, Object... obj) {
        int row = 0;
        try {
            connect();
            ps = conn.prepareStatement(sql);
            if (obj != null) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i + 1, obj[i]);
                }
                row = ps.executeUpdate();
            }
            close(conn, null, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 查询数据
     *
     * @param sql
     * @param obj
     * @return
     */
    public void executeQuery(String sql, Object... obj) {
        try {
            connect();
            ps = conn.prepareStatement(sql);
            if (obj != null) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i + 1, obj[i]);
                }
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭流
     *
     * @param conn
     * @param ps
     * @param rs
     */
    public void close(Connection conn, PreparedStatement ps, ResultSet rs) {

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
原文地址:https://www.cnblogs.com/gun-a/p/10535342.html