1 新建maven的java工程,pom文件导入mysql的坐标
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> <scope>runtime</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
2 项目结构截图
3 部分代码
ItemsDaoImpl.java
package com.sui.dao.impl; import com.sui.dao.ItemsDao; import com.sui.domain.Items; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ItemsDaoImpl implements ItemsDao { public List<Items> findAll() throws Exception{ Connection connection = null; CallableStatement pst = null; ResultSet rs = null; ArrayList<Items> list = new ArrayList<Items>(); try { // 加载驱动类 Class.forName("com.mysql.jdbc.Driver"); //获取connection对象 connection = DriverManager.getConnection("jdbc:mysql:///maven","root","123456"); //获取真正操作数据库的对象 pst = connection.prepareCall("select * from items"); //执行数据库查询操作 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 (Exception e) { e.printStackTrace(); } finally { connection.close(); pst.close(); rs.close(); } return list; } }
完毕,附代码。