package databaseOperate; public class Person { private int perId; private String name; private String addr; public int getPerId() { return perId; } public Person(String name, String addr) { super(); this.name = name; this.addr = addr; } @Override public String toString() { return "Person [perId=" + perId + ", name=" + name + ", addr=" + addr + "]"; } public void setPerId(int perId) { this.perId = perId; } public Person(int perId, String name, String addr) { super(); this.perId = perId; this.name = name; this.addr = addr; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } }
package databaseOperate; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class MysqlCon { private Connection con; private PreparedStatement ps; private static final String URL="jdbc:mysql://localhost:3306/hibernate"; public static void main(String[] args) { // new MysqlCon().updatePerson(new Person(2,"mm","beijing")); new MysqlCon().findAllPerson(); } public void findAllPerson(){ List<Person> list=new ArrayList<Person>(); try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(URL,"root","123"); ps=con.prepareStatement("select * from t_person"); ResultSet rs=ps.executeQuery(); while(rs.next()){ Person p=new Person(rs.getInt(1),rs.getString(2),rs.getString(3)); list.add(p); } con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } for(Person p:list){ System.out.println(p); } } public void updatePerson(Person p){ try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(URL,"root","123"); ps=con.prepareStatement("update t_person set perName=?,addr=? where perId=?"); ps.setString(1,p.getName()); ps.setString(2,p.getAddr()); ps.setInt(3,p.getPerId()); ps.execute(); con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void deletePerson(Person p){ try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(URL,"root","123"); ps=con.prepareStatement("delete from t_person where perId=?"); ps.setInt(1,p.getPerId()); ps.execute(); con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void savePerson(Person p){ try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(URL,"root","123"); ps=con.prepareStatement("insert into t_person(perName,addr) values(?,?)"); ps.setString(1,p.getName()); ps.setString(2,p.getAddr()); ps.execute(); con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
jdbc mysql
最新推荐文章于 2022-04-18 08:00:00 发布