zoukankan      html  css  js  c++  java
  • 温故知新 jdbc 数据库调取封装

    本方法没有用到(SSM)的xml层直接在service层调用,当遇到较为复杂的sql语句建议使用xml来查询

    注意导入mysql-connector-java-5.1.6-bin.jar 地址:

    链接: https://pan.baidu.com/s/187u9AMzeLaoUTIjW-MEHwQ 提取码: h9zi

    public List<Person> getPersonList() throws ClassNotFoundException, SQLException {

    List<Person> list=new ArrayList<Person>();
    //加载驱动
    Class.forName("com.mysql.jdbc.Driver");


    //获取连接
    String url="jdbc:mysql://localhost:3306/hmz?user=root&password=root&userUnicode=true&characterEncoding=UTF-8";
    Connection conn=DriverManager.getConnection(url);
    //产生对象
    Statement stat=conn.createStatement();
    //sql语句执行(自定义CRUD)
    String sql="select * from student";
    //执行sql语句方式一(不建议使用此方式)
    //ResultSet rs=stat.executeQuery(sql);

    //执行sql语句方式二(项目常用)
    PreparedStatement pstmt = conn.prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();

    //数据库中Student表中字段为 id  name age sex
    while(rs.next()){
    String id=rs.getString("SId");
    String name=rs.getString("Sname");
    Date age=rs.getDate("Sage");
    String sex=rs.getString("Ssex");

    //Person类中包含全参构造器,对应属性有 id, name ,age ,sex
    Person person=new Person(id,name,age,sex);
    list.add(person);
    }

    //关闭流

    rs.close();

    //遍历获取到的数据(这一步知识校验数据是否获取,项目中使用bebug模式可取消该步)
    for(Person personlist:list) {
    System.out.println(personlist);
    }

    return list;
    }

  • 相关阅读:
    Path Sum II
    Convert Sorted Array to Binary Search Tree
    Construct Binary Tree from Inorder and Postorder Traversal
    Construct Binary Tree from Preorder and Inorder Traversal
    Maximum Depth of Binary Tree
    Binary Tree Zigzag Level Order Traversal
    Binary Tree Level Order Traversal
    Same Tree
    Validate Binary Search Tree
    Binary Tree Inorder Traversal
  • 原文地址:https://www.cnblogs.com/pureray-hui/p/12558728.html
Copyright © 2011-2022 走看看