java连接数据库JDBC

兜兜转转最后还是得学java,当初就是因为eclipse太丑而拒绝入行java,最后还是迫于现实重新拿起java,感觉亏啊,学完java就是一个搞过.net,摸过java,撸过ng,用过vue,学过uni-app的人了,后面再学个react,感觉完美了,O(∩_∩)O哈哈~。一个简单的JDBC连接

public static void main(String[] args) {
     
     Connection con = null;
     Statement stmt = null;
     ResultSet result = null;
     try {
     
     	 // 1导入连接数据的jar包之后注册驱动
     	 // 注意驱动名称,jdk1.8的mysql驱动名多了个cj
         Class.forName("com.mysql.cj.jdbc.Driver");
         // 2获取连接数据库对象
         // 这里还要注意数据名称之后要加上时区,不然报错,也是因为jdk1.8的原因
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_study?serverTimezone=GMT%2B8","root","root");
         // 3sql语句
         String sql = "select * from student";
         // 4获取执行sql的对象
         stmt = con.createStatement();
         // 5执行sql获得返回值,查询语句返回的是ResultSet对象,需要用next方法读取,更新删除方法返回影响甚微行数
         result = stmt.executeQuery(sql);
         // next方法,读取到数据集的最后一行之后会返回false
         while (result.next()) {
     
             System.out.println(result.getString("name"));
         }
     } catch (ClassNotFoundException e) {
     
         e.printStackTrace();
     } catch (SQLException throwables) {
     
         throwables.printStackTrace();
     } finally {
     
     	 // 最后把相关的连接关闭
     	 if(result!=null){
     
                try {
     
                    result.close();
                } catch (SQLException throwables) {
     
                    throwables.printStackTrace();
                }
         }
         if (stmt != null) {
     
             try {
     
                 stmt.close();
             } catch (SQLException throwables) {
     
                 throwables.printStackTrace();
             }
         }
         if (con != null) {
     
             try {
     
                 con.close();
             } catch (SQLException throwables) {
     
                 throwables.printStackTrace();
             }
         }
     }
     // String sql="update student set age=20 where id='1'";
     // int i=stmt.executeUpdate(sql);
     // System.out.println(i);
 }

你可能感兴趣的:(java)