java:連接數(shù)據(jù)庫出錯

  • 11.5更新

寫的時候用的是Statement,后來看到網(wǎng)上說Statement有SQL風險,用PreStatement更好。我沒想明白是怎么回事,在窗體中看不到什么SQL風險,后來在學習EE的時候,明白了什么是SQL注入。最后在框架學習中,


忘記寫Mysql打開的事兒了
在我的電腦右鍵管理 ->服務與應用程序 ->服務 ->打幾個m就出來啦


一直連接數(shù)據(jù)庫出錯,最后發(fā)先數(shù)據(jù)庫沒有打開。囧

數(shù)據(jù)庫連接在新手中一直是個小小坎。在java中數(shù)據(jù)庫連接寫的東西很多,但是真正達到我們想要的就只有那么一兩句話。

有一堆的code復用,這個時候就開始封裝。

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class DBConnection {

    private DBConnection(){};
    
    private static Connection connection;
    
    static String classDriver = "com.mysql.jdbc.Driver";
    static String username = "root";
    static String password = "自己的密碼";
    static String url ="jdbc:mysql://localhost:3306/MISDB" ;
        
    public static Connection getConnection() throws SQLException {
        
        try {
            Class.forName(classDriver);
            if (connection == null) {
                connection = DriverManager.getConnection(url, username, password);
            }else {
                return connection;
            }
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 關閉三個參數(shù)
     * @param resultSet 記錄集
     * @param statement 聲明
     * @param connection 連接對象
     * @throws SQLException 
     */
    public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
        if (resultSet !=null) {
            resultSet.close();
        }if (statement != null) {
            statement.close();
        }if (connection != null) {
            connection.close();
        }
        
    }
    /**
    * @overRidden
    * @param statement
    * @param connection
    * @throws SQLException 
    */
    public static void closeConnection(Statement statement, Connection connection) throws SQLException{
        if (statement != null) {
             statement.close();
        }if (connection != null) {
             connection.close();
        }
    }
}

PS:第一次用代碼縮進很差,抱拳了老鐵

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容