maven工程(二)运行环境修改和获取mysql数据库数据
作者:互联网
运行环境修改
可以加上这个进行定义,你tomcat运行的端口
<build> <plugins> <plugin> <!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin --> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8888</port> </configuration> </plugin> </plugins> </build>
获取mysql数据库数据
表:
CREATE TABLE province( -- 创建表 id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL ); -- 插入数据 INSERT INTO province VALUES(NULL,'北京'); INSERT INTO province VALUES(NULL,'上海'); INSERT INTO province VALUES(NULL,'广州'); INSERT INTO province VALUES(NULL,'陕西');
导入mysql
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency>
Items:实体类
public class Items { private int id; private String 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; } }
ItemsDao:
public interface ItemsDao { public List<Items> findAll(); }
ItemsDaoImpl:
public class ItemsDaoImpl implements ItemsDao { @Override public List<Items> findAll() { ArrayList<Items> list = new ArrayList<>(); Connection connection = null; CallableStatement pst = null; ResultSet rs = null; try { //加载驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); //先获取contection对象 connection = DriverManager.getConnection("jdbc:mysql:///db2","root","root"); //获取真正操作数据对象 pst = connection.prepareCall("select * from province"); //执行数据库查询操作 rs = pst.executeQuery(); //把数据库结果集转成java的List集合 while (rs.next()){ Items items = new Items(); items.setId(rs.getInt("id")); items.setName(rs.getString("name")); list.add(items); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { if (rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (connection!=null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (pst!=null){ try { pst.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } return list; } }
测试类:
public class ItemsTest { @Test public void findAll(){ ItemsDao itemsDao = new ItemsDaoImpl(); List<Items> list = itemsDao.findAll(); for (Items items : list) { System.out.println(items.getName()); } } }
搜索
复制
标签:name,rs,throwables,数据库,id,maven,mysql,public 来源: https://www.cnblogs.com/pengtianyang/p/16615270.html