首頁 資料庫 mysql教程 JDBC 操作数据库

JDBC 操作数据库

Jun 07, 2016 pm 03:35 PM
jdbc 使用 操作 資料庫 框架

有时候 使用框架,或许没有直接操作数据库来的快, 或者说是使用框架太麻烦,有个直接操作数据库的工具类多好,故直接上干货,写下如下代码: private static Logger logger = Logger.getLogger(DBHelper.class.getName()); /** * 纯 java 式的连接 定义常量

            有时候

           使用框架,或许没有直接操作数据库来的快,

           或者说是使用框架太麻烦,有个直接操作数据库的工具类多好,故直接上干货,写下如下代码:


    private static Logger logger = Logger.getLogger(DBHelper.class.getName());
    /**
     * 纯 java 式的连接 定义常量来存储配置
     */
    public static String DRIVER = null;
    public static String URL = null;
    public static String USER = null;
    public static String PASS = null;

    Connection conn = null;
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet rs = null;

    // 获得数据连接信息.
    static {
        Properties pops = new Properties();
        InputStream inStream;
        try {
            inStream = DBCommandUtils.class.getResourceAsStream("/jdbc.properties");
            pops.load(inStream);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        URL = pops.getProperty("datasource.url");
        USER = pops.getProperty("datasource.username");
        PASS = pops.getProperty("datasource.password");
        DRIVER = pops.getProperty("datasource.driverClassName");
    }

    /**
     * 得到数据库连接
     */
    public Connection getConn() {
        try {
            if (DRIVER == null || USER == null || PASS == null || URL == null) {
                Properties pops = new Properties();
                InputStream inStream;
                try {
                    inStream = DBCommandUtils.class
                            .getResourceAsStream("/jdbc.properties");
                    pops.load(inStream);
                } catch (FileNotFoundException e) {
                    logger.error(e.getMessage());
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }

                URL = pops.getProperty("datasource.url");
                USER = pops.getProperty("datasource.username");
                PASS = pops.getProperty("datasource.password");
                DRIVER = pops.getProperty("datasource.driverClassName");
            }
            // 获得链接.
            Class.forName(DRIVER);
            conn = (Connection) DriverManager.getConnection(URL, USER, PASS);
            return conn;
        } catch (Exception e) {
            logger.error("获取链接失败!" + e.getLocalizedMessage());
            return null;
        }
    }

    /**
     * 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
     */
    public int executeSQL(String preparedSql, String[] param) {
        int count = 0;
        /**
         * 执行的操作
         */
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
            if (param != null) {
                for (int i = 0; i                     pstmt.setString(1 + i, param[i]);// 为预编译sql设置参数
                }
            }
            count = pstmt.executeUpdate(); // 执行 sql 语句
        } catch (SQLException e) {
            logger.error(e.getMessage()); // 处理SQLException异常
            return -1;
        }
        return count; // 返回结果
    }

    /**
     * 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
     */
    public int executeSQL(String preparedSql) {
        int count = 0;
        /**
         * 执行的操作
         */
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
            count = pstmt.executeUpdate(); // 执行 sql 语句
        } catch (SQLException e) {
            logger.error(e.getMessage()); // 处理SQLException异常
            return -1;
        }
        return count; // 返回结果
    }

    /**
     * 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
     */
    public int[] executeSQLs(String[] sqls) {
        int[] count = null;
        /**
         * 执行的操作
         */
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            stmt = conn.createStatement();
            for (String sql : sqls) {
                stmt.addBatch(sql);
            }
            count = stmt.executeBatch(); // 执行 sql 语句
        } catch (SQLException e) {
            logger.error(e.getMessage()); // 处理SQLException异常
            return null;
        }
        return count; // 返回结果
    }

    /**
     * 要执行的复杂操作
     */
    public boolean executeAllSQL(String preparedSql) {
        boolean result = false;
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
            result = pstmt.execute();
        } catch (SQLException e) {
            logger.error(e.getMessage()); // 处理SQLException异常
        }
        return result; // 返回结果
    }

    /**
     * 使用PreparedStatement查询数据
     *
     * @param sql
     * @param params
     *            参数列表
     * @return 结果集 不要关闭连接
     */
    public ResultSet selectSQL(String sql, String[] param) {
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            pstmt = conn.prepareStatement(sql); // 执行sql语句
            for (int i = 0; i                 pstmt.setString(i + 1, param[i]);
            }
            rs = pstmt.executeQuery(); // 执行的结果
        } catch (SQLException e1) {
            logger.error(e1.getMessage());
        }
        return rs;
    }

    /**
     * 使用statement执行查询
     *
     * @param sql
     *            执行的SQL语句
     * @return 不可关闭连接
     */
    public ResultSet selectSQL(String sql) {
        try {
            if (conn == null) {
                conn = getConn(); // 获得连接
            }
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
        } catch (SQLException e1) {
            logger.error(e1.getMessage());
        }
        return rs;
    }

    /**
     * 关闭所有的接口 (注意括号中的参数)
     */
    public void closeAll() {
        if (stmt != null) {
            try {
                stmt.close();
                stmt = null;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        // 判断是否关闭,要时没有关闭,就让它关闭,并给它附一空值(null),下同
        if (pstmt != null) {
            try {
                pstmt.close();
                pstmt = null;
            } catch (SQLException e) {
                logger.error(e.getMessage()); // 异常处理
            }
        }
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                logger.error(e.getMessage()); // 异常处理
            }
        }
        if (conn != null) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                logger.error(e.getMessage()); // 异常处理
            }
        }
    }

    /**
     * 检查数据库连接
     *
     * @param manager
     * @return true:无法连接;false:正常
     */
    public boolean checkCon(DBCommandUtils manager) {
        boolean result = false;
        try {
            result = getConn().isClosed();
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 编写测试类来进行对数据库的检验
     */
    public static void main(String[] args) {
        DBCommandUtils manager = new DBCommandUtils();
        try {
            System.out.println(manager.getConn().isClosed());
        } catch (SQLException e) {
            logger.error(e.getMessage()); // 抛出异常
        }
    }


这个玩意就可以直接拿来用了,其实还是很不错的玩意。。。

自然是没有使用关系型框架舒服了。

不过: 有了这个有时候不用框架也是比较舒服的。


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

iOS 18 新增「已復原」相簿功能 可找回遺失或損壞的照片 iOS 18 新增「已復原」相簿功能 可找回遺失或損壞的照片 Jul 18, 2024 am 05:48 AM

蘋果公司最新發布的iOS18、iPadOS18以及macOSSequoia系統為Photos應用程式增添了一項重要功能,旨在幫助用戶輕鬆恢復因各種原因遺失或損壞的照片和影片。這項新功能在Photos應用的"工具"部分引入了一個名為"已恢復"的相冊,當用戶設備中存在未納入其照片庫的圖片或影片時,該相冊將自動顯示。 "已恢復"相簿的出現為因資料庫損壞、相機應用未正確保存至照片庫或第三方應用管理照片庫時照片和視頻丟失提供了解決方案。使用者只需簡單幾步

如何評估Java框架商業支援的性價比 如何評估Java框架商業支援的性價比 Jun 05, 2024 pm 05:25 PM

評估Java框架商業支援的性價比涉及以下步驟:確定所需的保障等級和服務等級協定(SLA)保證。研究支持團隊的經驗和專業知識。考慮附加服務,如昇級、故障排除和效能最佳化。權衡商業支援成本與風險緩解和提高效率。

如何在PHP中處理資料庫連線錯誤 如何在PHP中處理資料庫連線錯誤 Jun 05, 2024 pm 02:16 PM

PHP處理資料庫連線報錯,可以使用下列步驟:使用mysqli_connect_errno()取得錯誤代碼。使用mysqli_connect_error()取得錯誤訊息。透過擷取並記錄這些錯誤訊息,可以輕鬆識別並解決資料庫連接問題,確保應用程式的順暢運作。

PHP 框架的學習曲線與其他語言框架相比如何? PHP 框架的學習曲線與其他語言框架相比如何? Jun 06, 2024 pm 12:41 PM

PHP框架的學習曲線取決於語言熟練度、框架複雜性、文件品質和社群支援。與Python框架相比,PHP框架的學習曲線較高,而與Ruby框架相比,則較低。與Java框架相比,PHP框架的學習曲線中等,但入門時間較短。

什麼是Bitget Launchpool?如何使用Bitget Launchpool? 什麼是Bitget Launchpool?如何使用Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool是一個為所有加密貨幣愛好者而設計的動態平台。 BitgetLaunchpool以其獨特的產品脫穎而出。在這裡,您可以質押您的代幣來解鎖更多獎勵,包括空投、高額回報,以及專屬早期參與者的豐厚獎金池。什麼是BitgetLaunchpool? BitgetLaunchpool是一個加密貨幣平台,可以透過使用者友善的條款和條件來質押和賺取代幣。透過在Launchpool中投入BGB或其他代幣,用戶有機會獲得免費空投、收益和參與豐厚的獎金池。質押資產的收益在T+1小時內計算,獎勵按

PHP 框架的輕量級選項如何影響應用程式效能? PHP 框架的輕量級選項如何影響應用程式效能? Jun 06, 2024 am 10:53 AM

輕量級PHP框架透過小體積和低資源消耗提升應用程式效能。其特點包括:體積小,啟動快,記憶體佔用低提升響應速度和吞吐量,降低資源消耗實戰案例:SlimFramework創建RESTAPI,僅500KB,高響應性、高吞吐量

Astar質押原理、收益拆解、空投項目及策略 & 操作保姆級攻略 Astar質押原理、收益拆解、空投項目及策略 & 操作保姆級攻略 Jun 25, 2024 pm 07:09 PM

目錄Astar Dapp 質押原理質押收益 拆解潛在空投項目:AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap 質押策略 & 操作“AstarDapp質押”今年初已升級至V3版本,對質押收益規則做了不少調整。目前首個質押週期已結束,第二質押週期的「投票」子週期剛開始。若要獲得「額外獎勵」收益,需掌握此關鍵階段(預計持續至6月26日,現餘不到5天)。我將細緻拆解Astar質押收益,

如何在 Golang 中將 JSON 資料保存到資料庫中? 如何在 Golang 中將 JSON 資料保存到資料庫中? Jun 06, 2024 am 11:24 AM

可以透過使用gjson函式庫或json.Unmarshal函數將JSON資料儲存到MySQL資料庫中。 gjson函式庫提供了方便的方法來解析JSON字段,而json.Unmarshal函數需要一個目標類型指標來解組JSON資料。這兩種方法都需要準備SQL語句和執行插入操作來將資料持久化到資料庫中。

See all articles