码迷,mamicode.com
首页 > 数据库 > 详细

mysql ----BaseDao工具类

时间:2019-03-15 10:33:31      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:connect   void   rest   stat   ret   nal   cal   catch   tco   

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();
            }
        }
    }
}

 

mysql ----BaseDao工具类

标签:connect   void   rest   stat   ret   nal   cal   catch   tco   

原文地址:https://www.cnblogs.com/gun-a/p/10535342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!