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()); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix