美文网首页
java:连接数据库出错

java:连接数据库出错

作者: leiheng | 来源:发表于2017-05-21 14:00 被阅读0次
    • 11.5更新

    写的时候用的是Statement,后来看到网上说Statement有SQL风险,用PreStatement更好。我没想明白是怎么回事,在窗体中看不到什么SQL风险,后来在学习EE的时候,明白了什么是SQL注入。最后在框架学习中,


    忘记写Mysql打开的事儿了
    在我的电脑右键管理 ->服务与应用程序 ->服务 ->打几个m就出来啦


    一直连接数据库出错,最后发先数据库没有打开。囧

    数据库连接在新手中一直是个小小坎。在java中数据库连接写的东西很多,但是真正达到我们想要的就只有那么一两句话。

    有一堆的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;
        }
    
        /**
         * 关闭三个参数
         * @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:第一次用代码缩进很差,抱拳了老铁

    相关文章

      网友评论

          本文标题:java:连接数据库出错

          本文链接:https://www.haomeiwen.com/subject/rfomxxtx.html