数据库连接_留着以后copy

来源:互联网 发布:上海美猴网络骗局 编辑:程序博客网 时间:2024/06/03 20:15

数据库连接_留着以后copy

自己写的东西,每次用到数据库都得敲一遍,懒人一个,写出来等哪天用得到直接copy。

代码块

import java.sql.*;public class BaseDao {    private Connection conn;    private PreparedStatement ps;    private ResultSet rs;    // 获得连接    private void getConnection() {        try {            Class.forName("com.mysql.jdbc.Driver");            String url = "jdbc:mysql://localhost:3306/tushuguan";            conn = DriverManager.getConnection(url, "root", "");        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        }    }    // 关闭    public void close() {        if (rs != null) {            try {                rs.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (ps != null) {            try {                ps.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }    // 更新---增加,修改,删除    public int executeUpdate(String sql, Object... objects) {        try {            this.getConnection();            ps = conn.prepareStatement(sql);            if (objects != null)// 设置参数                for (int i = 0; i < objects.length; i++) {                    ps.setObject(i + 1, objects[i]);                }            return ps.executeUpdate();        } catch (SQLException e) {            e.printStackTrace();        } finally {            this.close();        }        return -1;    }    //查询    public ResultSet executeQuery(String sql,Object...objects){        try {            this.getConnection();            ps = conn.prepareStatement(sql);            if (objects != null)// 设置参数                for (int i = 0; i < objects.length; i++) {                    ps.setObject(i + 1, objects[i]);                }            return ps.executeQuery();        } catch (SQLException e) {            e.printStackTrace();        }         return null;    }}
0 0
原创粉丝点击