maven的java工程取mysql数据库数据
maven的java工程取mysql数据库数据
创建User实体类:
public class User { private int id; private String NAME; @Override public String toString() { return "User{" + "id=" + id + ", NAME='" + NAME + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNAME() { return NAME; } public void setNAME(String NAME) { this.NAME = NAME; } }
在pom.xml中配置mysql驱动jar包
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.29</version> </dependency>
UserDao接口:
public interface UserDao { public List<User> findAll(); }
UserDaoImpl实现类:
public class UserDaoImpl implements UserDao { @Override public List<User> findAll(){ List<User> list = null; Connection connection = null; PreparedStatement pst = null; ResultSet rs = null; try { //加载驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); //获取connection对象 connection = DriverManager.getConnection("jdbc:mysql:///day23","root","root"); //获取真正操作数据的对象 pst = connection.prepareCall("select * from province"); //执行数据库查询操作 rs = pst.executeQuery(); //把数据库结果集转成java的List集合 list = new ArrayList<>(); while (rs.next()){ User user = new User(); user.setId(rs.getInt("id")); user.setNAME(rs.getString("NAME")); list.add(user); } } catch (Exception e) { e.printStackTrace(); }finally { try { connection.close(); pst.close(); rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } return list; } }
UserTest测试:
public class UserTest { @Test public void findAll(){ UserDao user = new UserDaoImpl(); List<User> list = user.findAll(); for (User user1 : list) { System.out.println(user1); } } }
标签:java,NAME,rs,list,id,maven,mysql,public From: https://www.cnblogs.com/qihaokuan/p/17113934.html