• Java数据库操作包装类


    DbBean的功能扩展 * 更方便的完成数据库操作
    import java.sql.ResultSet;

    /**
    * DbBean的功能扩展
    * 更方便的完成数据库操作
    */
    public class DbAccess extends DbBean {

    //初始化数据源URL和数据库驱动,数据库用户名和密码
    public DbAccess(String _url, String _driver, String _username,String _password) {
    super(_url,_driver,_username,_password);
    }

    // 初始化数据源URL和数据库驱动
    public DbAccess(String _url, String _driver) {
    super(_url,_driver);
    }

    // 执行查询操作并返回结果集,返回表中所有元素
    public ResultSet doSelect(String _tablename) {

    ResultSet rs = null;

    try {
    String sql = "select * from " + _tablename;
    rs = super.getResult(sql);
    } catch (Exception e) {
    System.out.println("doSelect操作出错");
    }

    return rs;

    }

    // 执行查询操作并返回结果集,返回指定元素
    public ResultSet doSelect(String _tablename, String _wheresql) // _wheresql代表where之后的sql语句
    {

    ResultSet rs = null;

    try {
    String sql = "select * from " + _tablename + " where " + _wheresql;
    rs = super.getResult(sql);
    } catch (Exception e) {
    System.out.println("doSelect操作出错");
    }

    return rs;

    }

    // 删除符合条件的行
    public void doDelete(String _tablename, String _wheresql) {
    try {
    String sql = "delete * from " + _tablename + " where " + _wheresql;
    super.dbUpdate(sql, false);
    } catch (Exception e) {
    System.out.println("doDelete操作出错");
    }
    }

    // 执行删除操作
    public void doDelete(String _tablename, String _names, String _wheresql)// _names代表所要删除的字段名或_names
    // =
    // "*"
    {
    try {
    String sql = "delete (" + _names + ") from " + _tablename
    + " where " + _wheresql;
    super.dbUpdate(sql, false);
    } catch (Exception e) {
    System.out.println("doDelete操作出错");
    }
    }

    // 删除所有行
    public void doDelete(String _tablename) {
    try {
    String sql = "delete from " + _tablename;
    super.dbUpdate( sql, false);
    } catch (Exception e) {
    System.out.println("doDelete操作出错");
    }
    }

    // 执行插入操作
    public void doInsert(String _tablename, String _values)// _values是所要入元素的值
    {
    try {
    String sql = "insert into " + _tablename + " values (" + _values
    + ")";
    super.dbUpdate(sql, false);
    } catch (Exception e) {
    System.out.println("doDelete操作出错");
    }
    }

    // 执行插入操作
    public void doInsert(String _tablename, String _names, String _values)// _names是所要插入的字段名
    //
    // _values是所要入元素的值
    {
    try {
    String sql = "insert into " + _tablename + " (" + _names
    + ") values (" + _values + ")";
    super.dbUpdate(sql, false);
    } catch (Exception e) {
    System.out.println("doDelete操作出错");
    }
    }

    // 执行修改操作
    public void doUpdate(String _tablename, String _values, String _wheresql)// _values是所要修改元素和值
    // ,
    // _wheresql代表where之后的sql语句
    {
    try {
    String sql = "update " + _tablename + " set " + _values + " where "
    + _wheresql;
    super.dbUpdate(sql, false);
    } catch (Exception e) {
    System.out.println("doUpdate操作出错");
    }
    }

    }

    数据库包装类

    View Code
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.PreparedStatement;
    import java.sql.CallableStatement;
    import java.sql.ResultSet;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Types;

    /**
    * 该类用于封装数据库操作
    */
    public class DbBean {

    private String URL=null;// 数据源URL
    private String DRIVER=null;// 数据库驱动
    private String USERNAME=null;//用戶名
    private String PASSWORD=null;//密碼
    private String SQL=null;// SQL语句
    private boolean ISQUERY = true;// 判断是QUERY操作或UPDATE操作默认为QUERY
    private Connection CON=null;// 语句对象
    private Statement SM=null;// 语句对象
    private PreparedStatement PSM=null;// Prepared语句对象
    private CallableStatement CSM=null;// 执行存储过程的语句对象
    private ResultSet RS=null;// 结果集对象

    public DbBean() {

    }

    public DbBean(String _url, String _driver) {
    this.URL = _url;
    this.DRIVER = _driver;
    }

    public DbBean(String _url, String _driver, String _username,String _password) {
    this.URL = _url;
    this.DRIVER = _driver;
    this.USERNAME = _username;
    this.PASSWORD = _password;
    }

    // 开启数据库连接
    public void openCon() {
    SM = this.makeStatement();
    }

    // 用于执行select操作
    public ResultSet getResult(String _sql) {
    SQL = _sql;
    return this.runExecute();
    }

    // 用于执行insert,delete,update操作
    public void dbUpdate(String _sql,boolean _isquery) {
    SQL = _sql;
    ISQUERY = _isquery;
    this.runExecute();
    }

    // 用于初始化prepared语句对象
    public void dbPrepared(String _sql) {
    PSM = this.makePreparedStatement( _sql);
    SQL = _sql;
    }

    // 用于执行prepared语句的数据库操作
    public void runPrepared() {
    try {
    PSM.execute();
    System.out.println("执行prepared语句的数据库操作");
    } catch (Exception e) {
    System.out.println("执行prepared语句的数据库操作出错");
    }

    }

    // _values的值用于填充SQL语句中的?处的参数
    public void setPreparedVal(Object[] _values) {
    try {
    for (int i = 0; i < _values.length; i++) {
    PSM.setObject(i, _values[i]);
    }
    } catch (Exception e) {
    System.out.println("设置prepared的SQL语句的参数时出错");
    }

    }

    // _values的值用于填充SQL语句中的?处的String型的参数
    public void setPreparedValString(String[] _values) {
    try {
    for (int i = 0; i < _values.length; i++) {
    PSM.setString(i, _values[i]);
    }
    } catch (Exception e) {
    System.out.println("设置prepared的SQL语句的String型参数时出错");
    }

    }

    // _values的值用于填充SQL语句中的?处的int型参数
    public void setPreparedValInt(int[] _values) {
    try {
    for (int i = 0; i < _values.length; i++) {
    PSM.setInt(i, _values[i]);
    }
    } catch (Exception e) {
    System.out.println("设置prepared的SQL语句的int型参数时出错");
    }

    }

    //用于初始化执行存储过程的语句对象,_procedurename为存储过程名和参数列表用如"_Test[(?,?)]",有返回值时outval="?="
    // ;没有时outval="";
    public void dbCallable(String _url, String _driver, String _procedurename,
    String _outval) {
    CSM = this
    .makeCallableStatement(_procedurename, _outval);
    }

    // 设置存储过程的返回值
    public void setProcedureOut(int _sqlType) {
    try {
    CSM.registerOutParameter(0, _sqlType);
    } catch (Exception e) {
    System.out.println("设置存储过程的返回值时出错");
    }
    }

    // 获取存储过程的返回值
    public void getProcedureOut() {
    try {
    CSM.getObject(0);
    } catch (Exception e) {
    System.out.println("获取存储过程的返回值时出错");
    }
    }

    // 用于执行存储过程的数据库操作
    public void runCallable() {
    try {
    PSM.execute();
    System.out.println("执行存储过程的数据库操作");
    } catch (Exception e) {
    System.out.println("用于执行存储过程的数据库操作出错");
    }
    }

    // 可以在首次执行数据库操作后,再次操作时使用
    public ResultSet reExecute() {
    if (SQL != null) {
    return this.runExecute();
    } else {
    System.out.println("请先输入SQL语句");
    return null;
    }
    }

    // 设置SQL语句
    public void setSql(String _sql) {
    SQL = _sql;
    }

    // 设置数据库操作类型
    public void setIsquery(boolean _isquery) {
    ISQUERY = _isquery;
    }

    // 关闭数据库连接出错
    public void dbClose() {
    try {

    URL = null;
    DRIVER = null;
    SQL = null;
    ISQUERY = true;

    CON.commit();

    if (RS != null) {
    RS.close();
    }

    if (SM != null) {
    SM.close();
    }

    if (CON != null) {
    CON.close();
    }
    System.out.println("关闭数据库连接");
    } catch (Exception e) {
    System.out.println("关闭数据库连接出错");
    }

    }


    // 内部使用方法,用于创建语句对象
    private Statement makeStatement() {

    try {
    // 加载数据库驱动
    Class.forName(DRIVER);
    System.out.println("加载数据库驱动");
    } catch (Exception e) {
    System.out.println("无法加载数据库驱动");
    }

    Statement sm;
    try {
    // 创建数据库连接语句对象
    if ((USERNAME == null) && (PASSWORD == null)) {
    CON = DriverManager.getConnection(URL);
    } else {
    CON = DriverManager.getConnection(URL, USERNAME,PASSWORD);
    }
    sm = CON.createStatement();
    System.out.println("创建数据库连接");
    return sm;

    } catch (Exception e) {
    System.out.println("创建数据库连接语句对象出错");
    return null;
    }

    }

    // 内部使用方法,用于创建Prepared语句对象
    private PreparedStatement makePreparedStatement(String _preparedsql) {

    try {
    // 加载数据库驱动
    Class.forName(DRIVER);
    System.out.println("加载数据库驱动");
    } catch (Exception e) {
    System.out.println("无法加载数据库驱动");
    }

    PreparedStatement psm;
    try {
    // 创建数据库连接语句对象
    CON = DriverManager.getConnection(URL);
    psm = CON.prepareStatement(_preparedsql);
    System.out.println("创建数据库连接");
    return psm;

    } catch (Exception e) {
    System.out.println("创建数据库连接Prepared语句对象出错");
    return null;
    }

    }

    // 内部使用方法,用于创建执行存储过程的语句对象
    private CallableStatement makeCallableStatement(String _procedurename, String _outval) {

    try {
    // 加载数据库驱动
    Class.forName(DRIVER);
    System.out.println("加载数据库驱动");
    } catch (Exception e) {
    System.out.println("无法加载数据库驱动");
    }

    CallableStatement csm;
    try {
    // 创建数据库连接语句对象
    CON = DriverManager.getConnection(URL);
    csm = CON.prepareCall("{" + _outval + "call " + _procedurename
    + "}");
    System.out.println("创建数据库连接");
    return csm;

    } catch (Exception e) {
    System.out.println("创建执行存储过程的语句对象出错");
    return null;
    }

    }

    // 内部使用方法,执行SQL语句并返回结果集
    private ResultSet runExecute() {
    try {
    if (ISQUERY) {
    RS = SM.executeQuery(SQL);
    System.out.println("执行数据库查询操作");
    return RS;
    } else {
    ISQUERY = true;
    SM.executeUpdate(SQL);
    System.out.println("执行数据库更新操作");
    return null;
    }
    } catch (Exception e) {
    System.out.println("执行SQL语句出错");
    return null;
    }

    }

    }



    新类:

    1 此类为数据库参数获取类:

    package com.db;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.util.Properties;

    /**
    * 数据库访问配置文件各参数的获取
    *
    @author lzx
    *
    */
    public class DbConfig {
    //数据库及server配置文件路径
    private static final String ACTIONPATH = "config.properties"; //配置文件位置
    private static DbConfig instance=null;

    private String db_username=null;
    private String db_password=null;
    private String db_name=null;
    private String ip=null;
    private String ags_user=null;
    private String ags_password=null;
    private String ags_domain=null;
    private String ags_host=null;
    private String ags_servicename=null;

    private DbConfig(){}

    public String getDb_username() {
    return db_username;
    }
    public String getDb_password() {
    return db_password;
    }
    public String getDb_name() {
    return db_name;
    }
    public String getIp() {
    return ip;
    }
    public String getAgs_user() {
    return ags_user;
    }
    public String getAgs_password() {
    return ags_password;
    }
    public String getAgs_domain() {
    return ags_domain;
    }
    public String getAgs_host() {
    return ags_host;
    }
    public String getAgs_servicename() {
    return ags_servicename;
    }

    public static DbConfig getInstance(){
    if(instance==null){
    instance= new DbConfig().getNewDbConfig();
    }
    return instance;
    }

    private DbConfig getNewDbConfig(){

    DbConfig dc=new DbConfig();
    Properties prop = new Properties();
    String path=null;
    FileInputStream fis=null;

    try {
    path = DbConfig.class.getClassLoader().getResource("").toURI().getPath();
    fis = new FileInputStream(new File(path + ACTIONPATH));
    prop.load(fis);
    dc.db_username=prop.getProperty("db_username");
    dc.db_password=prop.getProperty("db_password");
    dc.db_name=prop.getProperty("db_name");
    dc.ip=prop.getProperty("ip");
    dc.ags_user=prop.getProperty("ags_user");
    dc.ags_password=prop.getProperty("ags_password");
    dc.ags_domain=prop.getProperty("ags_domain");
    dc.ags_host=prop.getProperty("ags_host");
    dc.ags_servicename=prop.getProperty("ags_servicename");
    } catch (URISyntaxException e) {
    e.printStackTrace();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    return dc;
    }
    }



    2 此类为数据库连接工具类:

    package com.db;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import oracle.jdbc.driver.OracleDriver;

    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;

    /**
    * 数据库连接工具类
    *
    @version 1.0
    */
    public class JdbcConnection {

    // 定义线程本地变量,每个线程访问它都会获得不同的对象
    // 使用ThreadLocal使一个连接绑定到一个线程上
    private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
    private static String username=null; //用户名
    private static String password=null; //密码
    private static String dbName=null; //数据库名称
    private static String ip=null; //数据库服务器IP地址
    private static String resourceName=null; //为null时不使用连接池, jdbc/mysql或jdbc/oracle或jdbc/derby
    private static String databaseType = "oracle";

    private static void initParams(){
    username=DbConfig.getInstance().getDb_username();
    password=DbConfig.getInstance().getDb_password();
    dbName=DbConfig.getInstance().getDb_name();
    ip=DbConfig.getInstance().getIp();
    }

    /**
    *
    *
    @return 得到一个数据库连接
    *
    @throws SQLException
    */
    public static Connection getConnection() throws SQLException {
    Connection conn = currentConnection.get();
    if (conn == null) {
    if(null==resourceName){
    if("mysql".equals(databaseType.toLowerCase())){
    conn = getMySqlConnection();
    }else if("oracle".equals(databaseType.toLowerCase())){
    conn = getOracleConnection();
    }else if("derby".equals(databaseType.toLowerCase())){
    conn = getDerbyConnection();
    }else{
    System.out.println("在 JdbcConnection.java 中数据库类型没有设置");
    throw new SQLException("数据库类型未设置");
    }
    }else{
    conn = getConnectionByPool();
    }
    currentConnection.set(conn);
    }
    return conn;
    }
    /**
    * 关闭Oracle数据库连接
    *
    @throws SQLException
    */
    public static void closeConnection() throws SQLException{
    Connection conn = currentConnection.get();
    conn.close();
    currentConnection.set(null);
    }
    //获得Oracle数据库连接
    private static Connection getOracleConnection(){
    initParams();
    Connection conn = null;
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); //加载驱动
    conn= DriverManager.getConnection("jdbc:oracle:thin:@"+ip+":1521:"+dbName,username,password);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    System.out.println("Oracle驱动没找到");
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return conn;
    }
    //获得MySql数据库连接
    private static Connection getMySqlConnection(){
    initParams();
    Connection conn = null;
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance(); //加载驱动
    String url = "jdbc:mysql://"+ip+":3306/"+dbName+"?useUnicode=true&characterEncoding=utf8";
    conn = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    System.out.println("MySql驱动没找到");
    } catch (SQLException e) {
    e.printStackTrace();
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    return conn;
    }
    //获取Derby数据库连接
    private static Connection getDerbyConnection(){
    initParams();
    Connection conn = null;
    try {
    Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); //加载驱动
    String url = "jdbc:derby://"+ip+":1527/"+dbName+";create=true";
    conn = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    System.out.println("Derby驱动没找到");
    } catch (SQLException e) {
    e.printStackTrace();
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    return conn;
    }
    //获取连接池连接
    private static Connection getConnectionByPool(){
    try {
    Context ctx = new InitialContext();
    Context subContext = (Context)ctx.lookup("java:comp/env");
    String dsName="";
    dsName = resourceName;

    DataSource dataSource = (DataSource)subContext.lookup(dsName);
    //上面两句可以合写成下边这句
    //ctx.lookup("java:comp/env/jdbc/oracle");// java:comp/env/ 规定:加前缀指定资源
    return dataSource.getConnection();
    }
    catch (NamingException e) {e.printStackTrace();}
    catch (SQLException e) {e.printStackTrace();}
    return null;
    }
    }

    3 使用示例如下:

        public ArrayList<Map> getUncheckData(String tablename) {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    ArrayList<Map> result = new ArrayList<Map>();
    try {
    conn = JdbcConnection.getConnection();
    ps = conn.prepareStatement("select * from " + tablename + " where checkstatus=0");
    rs = ps.executeQuery();

    while (rs.next()) {
    //TODO
    }
    } catch (SQLException e) {
    e.printStackTrace();
    }

    return result;
    }


    4 对应的配置文件如下:

    #database username
    db_username=sde
    #database password
    db_password=sde
    #database server name
    db_name=RASA
    #database server ip
    ip=localhost
    #arcgis server username
    ags_user=zj
    #arcgis server password
    ags_password=0.
    #arcgis server user domain
    ags_domain=zj
    #arcgis server host address
    ags_host=localhost
    #arcgis server feature service name
    ags_servicename=map



  • 相关阅读:
    解决:Android 8.0检测不到当前的activity
    flask学习(十三):过滤器
    打开相册上传图片
    完整的项目
    解决ScrollView滑动RecyclerView的卡顿
    RxJava
    CoordinatorLayout
    NestedScrollView,RecyclerView
    ViewPageIndicator
    RxJava的实现原理
  • 原文地址:https://www.cnblogs.com/myparamita/p/1455024.html
Copyright © 2020-2023  润新知