JDBC ORM(Object Relationship Database Mapping)

ORM = Object Relationship Database Mapping

objects and relational database mapping

Simply put, an object of the corresponding database record

 

Example: The target returns an id Hero

The method provides get (int id)
Returns a target 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 = "Hero from the SELECT * the WHERE id =" + id; 
   
            ResultSet rs = s.executeQuery (SQL); 
   
            // because id is unique, ResultSet can have up to a record
             // So if instead of using the while 
            if (rs.next ()) { 
                Hero = new new Hero (); 
                String name = rs.getString (2 );
                 a 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 hero = get(2);
        System.out.println(hero.name+"的hp是"+hero.hp+",damage是"+hero.damage);
    }
}

 Output:

Timo's hp is 313.0, damage is 50

 

Guess you like

Origin www.cnblogs.com/churujianghudezai/p/11441257.html