您的位置:首页 > 数据库

jdbc数据库操作封装

2017-12-04 15:51 267 查看
package com.conn;

import com.conn.po.User;

import org.junit.Test;

import java.io.IOException;

import java.io.InputStream;

import java.lang.reflect.Field;

import java.sql.*;

import java.util.*;

public class DataConnection {

    private Connection connection;

    // 连接驱动*

    private String driver;

    // 数据库连接url

    private String url;

    // 数据库用户名

    private String username;

    // 数据库密码

    private String password;

    /**

     * 执行多条update,delete,insert into数据

     *

     * @param list<UpdateMulti>UpdateMultil

     * @return 返回受影响的数量

     */

    public int executeMulti(List<UpdateMulti> list) {

        int num = 0;

        PreparedStatement psmt = null;//用PreparedStatement 防止sql注入

        //判断连接是否为空,为空重新建立连接

        if (this.connection == null) {

            this.connection = this.getConnection();

        }

        //并判断连接是否建立成功,失败则返回0

        if (this.connection == null) {

            return num;

        }

        try {

            //封装成事务处理,保证数据的安全性

            this.connection.setAutoCommit(false);//设置事务

            if (list != null && !list.isEmpty()) {

                for (int i = 0; i < list.size(); i++) {

                    UpdateMulti um = list.get(i);

                    String sql = um.getSql();

                    List params = um.getParams();

                    psmt = this.connection.prepareStatement(sql);

                    if (params != null && !params.isEmpty()) {

                        int index = 1;

                        for (int ii = 0; ii < params.size(); ii++) {

                            psmt.setObject(index++, params.get(ii));

                        }

                    }

                    num += psmt.executeUpdate();

                }

                this.connection.commit();

            }

        } catch (SQLException e) {

            try {

                this.connection.rollback();

            } catch (SQLException e1) {

                e1.printStackTrace();

            }

            e.printStackTrace();

        }

        try {

            if (psmt != null) {

                psmt.close();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return num;

    }

    /**

     * 执行单条update,delete,insert into

     *

     * @param sql    带参数的sql

     * @param params 需要的条件,用PreparedStatement 防止sql注入

     * @return 返回受影响的数量

     */

    public int execute(String sql, List<Object> params) {

        int num = 0;//返回的受影响的条数

        PreparedStatement psmt = null;//用PreparedStatement 防止sql注入

        //判断连接是否为空,为空重新建立连接,并判断连接是否建立成功,失败则返回0

        if (this.connection == null) {

            this.connection = this.getConnection();

        }

        if (this.connection == null) {

            return num;

        }

        try {

            //封装成事务处理,保证数据的安全性

            this.connection.setAutoCommit(false);

            psmt = this.connection.prepareStatement(sql);

            //给PrepareStatement注入参数,PrepareStatement参数的下标是从1开始的,集合类是从0开始的

            if (params != null && !params.isEmpty()) {

                int index = 1;

                for (int i = 0; i < params.size(); i++) {

                    psmt.setObject(index++, params.get(i));

                }

            }

            num = psmt.executeUpdate();

            this.connection.commit();//提交

        } catch (SQLException e) {

            try {

                this.connection.rollback();

            } catch (SQLException e1) {

                e1.printStackTrace();

            }

            e.printStackTrace();

        }

        try {

            if (psmt != null) {

                psmt.close();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return num;

    }

    /*反射查询*/

    public <T> List<T> getObjectList(String sql, List<Object> params, Class<T> cls) {

        PreparedStatement psmt = null;

        ResultSet rs = null;

        List<T> list = new ArrayList<T>();

        if (this.connection == null) {

            this.connection = this.getConnection();

        }

        if (this.connection == null) {

            return null;

        }

        try {

            psmt = this.connection.prepareStatement(sql);

            if (params != null && !params.isEmpty()) {

                int index = 1;

                for (int i = 0; i < params.size(); i++) {

                    psmt.setObject(index++, params.get(i));

                }

            }

            rs = psmt.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();

            int columns = rsmd.getColumnCount();

            while (rs.next()) {

                T rsObject = cls.newInstance();

                for (int i = 0; i < columns; i++) {

                    String columnName = rsmd.getColumnName(i + 1);

                    Object columnValue = rs.getObject(columnName);

                    if (columnValue == null) {

                        columnValue = "";

                    }

                    Field field = cls.getDeclaredField(columnName);

                    field.setAccessible(true);

                    field.set(rsObject, columnValue);

                }

                list.add(rsObject);

            }

        } catch (Exception e) {

            System.out.println(e.getMessage());

        } finally {

            try {

                if (rs != null) {

                    rs.close();

                }

                if (psmt != null) {

                    psmt.close();

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return list;

    }

    /*直接查询*/

    public List<Map<String, Object>> getDataList(String sql, List<Object> params) {

        PreparedStatement psmt = null;

        ResultSet rs = null;

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        if (this.connection == null) {

            this.connection = this.getConnection();

        }

        if (this.connection == null) {

            return null;

        }

        try {

            psmt = this.connection.prepareStatement(sql);

            if (params != null && !params.isEmpty()) {

                int index = 1;

                for (int i = 0; i < params.size(); i++) {

                    psmt.setObject(index++, params.get(i));

                }

            }

            rs = psmt.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();

            int columns = rsmd.getColumnCount();

            while (rs.next()) {

                Map<String, Object> map = new HashMap<String, Object>();

                for (int i = 0; i < columns; i++) {

                    String columnName = rsmd.getColumnName(i + 1);

                    Object columnValue = rs.getObject(columnName);

                    map.put(columnName, columnValue);

                }

                list.add(map);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            try {

                if (rs != null) {

                    rs.close();

                }

                if (psmt != null) {

                    psmt.close();

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return list;

    }

    public void releaseConnection() {

        try {

            if (this.connection != null) {

                connection.close();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    private boolean setProperties() {

        String properties = "config/db.properties";

        InputStream is = ClassLoader.getSystemResourceAsStream(properties);

        Properties prop = new Properties();

        try {

            prop.load(is);

            this.driver = prop.getProperty("driver");

            this.url = prop.getProperty("url");

            this.username = prop.getProperty("username");

            this.password = prop.getProperty("password");

        } catch (IOException e) {

            e.printStackTrace();

            return false;

        }

        return true;

    }

    private Connection getConnection() {

        connection = null;

        if (!setProperties()) {

            return null;

        }

        try {

            Class.forName(this.driver);

            connection = DriverManager.getConnection(this.url, this.username, this.password);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return connection;

    }

    @Test

    public void test() {

        UpdateMulti um = new UpdateMulti();

        List<UpdateMulti> list_insert = new ArrayList<UpdateMulti>();

        um.setSql("insert into user(username,address,dept,account)values(?,?,?,?)");

        List<Object> list_params = new ArrayList<Object>();

        list_params.add("Rose");

        list_params.add("New york");

        list_params.add("sale");

        list_params.add(19000.00);

        um.setParams(list_params);

        list_insert.add(um);

        DataConnection dataConnection = new DataConnection();

       int num= dataConnection.executeMulti(list_insert);

        System.out.println("success in insert into "+num+ " data");

        String sql = "select * from user";

        List<Object> l1 = new ArrayList<Object>();

        List<User> list = (List<User>) dataConnection.getObjectList(sql, null, User.class);

        for (User u : list) {

            System.out.println(u.toString());

        }

    }
}

package com.conn;

import java.util.List;

/**

 * Created by Administrator on 17-12-4.

 */

public class UpdateMulti {

    private String sql;

    private List<Object> params;

    public List<Object> getParams() {

        return params;

    }

    public void setParams(List<Object> params) {

        this.params = params;

    }

    public String getSql() {

        return sql;

    }

    public void setSql(String sql) {

        this.sql = sql;

    }

}

package com.conn.po;

import java.io.Serializable;

/**

 * Created by Administrator on 17-12-4.

 */

public class User implements Serializable {

    private static final long serializableUID = 0;

    private Integer id;

    private String username;

    private String address;

    private String dept;

    private Double account;

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public String getDept() {

        return dept;

    }

    public void setDept(String dept) {

        this.dept = dept;

    }

    public Double getAccount() {

        return account;

    }

    public void setAccount(Double account) {

        this.account = account;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", username='" + username + '\'' +

                ", address='" + address + '\'' +

                ", dept='" + dept + '\'' +

                ", account=" + account +

                '}';

    }
}

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/dbtest?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

username=root

password=
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: