maven的java工程取mysql数据库数据

maven的java工程取mysql数据库数据

  • 需要导入的依赖
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
package com.itheima.pojo;

import java.util.Date;

public class Items {
    private Integer id;
    private String name;

    @Override
    public String toString() {
        return "Items{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Items(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Items() {
    }
}

dao

package com.itheima.dao;

import com.itheima.pojo.Items;


import java.sql.SQLException;
import java.util.List;

public interface ItemsDao {
    public List<Items> findAll() throws SQLException, ClassNotFoundException;
}

daoimpl

package com.itheima.dao.impl;

import com.itheima.dao.ItemsDao;
import com.itheima.pojo.Items;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ItemsDaoImpl implements ItemsDao {
    @Override
    public List<Items> findAll() throws SQLException, ClassNotFoundException {
        //加载驱动类
        Class.forName("com.mysql.cj.jdbc.Driver");
        //先获取contection对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/maven","root","root");
        //获取真正操作数据的对象
        CallableStatement pst = connection.prepareCall("select * from items");
        //执行数据库查询操作
        ResultSet rs = pst.executeQuery();
        //把数据库结果集转成java的list对象
        ArrayList<Items> list = new ArrayList<>();
        while (rs.next()) {
            Items items = new Items();
            items.setId(rs.getInt("id"));
            items.setName(rs.getString("name"));
            list.add(items);
        }
        connection.close();
        pst.close();
        rs.close();
        return list;
    }
}

数据库:
image

测试类:

package com.itheima.test;

import com.itheima.dao.impl.ItemsDaoImpl;
import com.itheima.pojo.Items;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;

public class MyTest {
    @Test
    public void Test01() throws SQLException, ClassNotFoundException {
        ItemsDaoImpl itemsDao = new ItemsDaoImpl();
        List<Items> all = itemsDao.findAll();
        all.forEach(items -> System.out.println(items));
    };
}

结果展示:
image

posted @ 2022-08-24 10:57  我滴妈老弟  阅读(83)  评论(0编辑  收藏  举报