JDBC ORM(Object Relationship Database Mapping)

匿名 (未验证) 提交于 2019-12-02 23:57:01

ORM=Object Relationship Database Mapping

对象和关系数据库的映射

简单说,一个对象,对应数据库里的一条记录

示例:根据id返回一个Hero对象

提供方法get(int id)
返回一个Hero对象

public class Hero {     //增加id属性     public int id;     public String name;     public float hp;     public int damage;   }
public class TestJDBC {         public static Hero get(int id) {         Hero hero = null;         try {             Class.forName("com.mysql.jdbc.Driver");         } catch (ClassNotFoundException e) {             e.printStackTrace();         }           try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");             Statement s = c.createStatement();) {               String sql = "select * from hero where id = " + id;                 ResultSet rs = s.executeQuery(sql);                 // 因为id是唯一的,ResultSet最多只能有一条记录             // 所以使用if代替while             if (rs.next()) {                 hero = new Hero();                 String name = rs.getString(2);                 float hp = rs.getFloat("hp");                 int damage = rs.getInt(4);                 hero.name = name;                 hero.hp = hp;                 hero.damage = damage;                 hero.id = id;             }             } catch (SQLException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         return hero;         }         public static void main(String[] args) {                     Hero h = get(22);         System.out.println(h.name);         } }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!