Java连接数据库,将查询到的table数据存入集合

1、预设在本地MySQL有一个数据库"database1",其内有table名为"lunch",如下图所示:

 2、新建一个java文件(这里简单用的Main)

import java.sql.*;
import java.util.*;

public class Main {    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//导入JDBC驱动程序
            Connection con = DriverManager.getConnection("jdbc:mysql:///c_a4_jdbc","root","root1234");//建立与数据库的连接
            Statement stmt = con.createStatement();//创建一个Statement对象
            ResultSet qry = stmt.executeQuery("SELECT * FROM lunch;");//执行SQL查询

 3、这个文件代码没写完,下面再看,我们先来为集合里面储存的对象创建一个类

package table;

public class Lunch {
	private int no;
	private String seto;
	private int price;
	private int number;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	
	public String getSeto() {
		return seto;
	}
	public void setSeto(String seto) {
		this.seto = seto;
	}
	
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
}
	

4、继续回到刚才的java文件

            List<Lunch> lunches = new ArrayList<>();//创建一个空集合
            while(qry.next()) {
                Lunch lunch = new Lunch();//创建lunch对象
                lunch.setNo(qry.getInt(1));
                lunch.setSeto(qry.getString(2));
                lunch.setPrice(qry.getInt(3));
                lunch.setNumber(qry.getInt(4));
                
                lunches.add(lunch);//将lunch对象添加到集合中
            }
            System.out.println(lunches);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }
        
    }

}

5、打印结果为:

[Lunch [no=1, seto=A, price=700, number=20], Lunch [no=2, seto=B, price=800, number=20], Lunch [no=3, seto=C, price=600, number=0], Lunch [no=4, seto=D, price=700, number=50]]

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值