首页 > 数据库技术 > 详细

使用jdbc,查询数据库数据,并将其封装为对象输出

时间:2019-08-14 01:08:18      阅读:164      评论:0      收藏:0      [点我收藏+]
package cn.itcast.jdbc;

import cn.itcast.domain.User;

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

/**
* @author newcityman
* @date 2019/8/13 - 23:27
*/
public class JDBCDemo06 {

public static void main(String[] args) {
JDBCDemo06 demo06 = new JDBCDemo06();
demo06.findAll();
}

public List<User> findAll() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<User> list = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day13", "root", "123");
stmt = conn.createStatement();
String sql = "select * from user";
rs = stmt.executeQuery(sql);
list = new ArrayList<User>();
User user = null;
//遍历集合
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
String sex = rs.getString("sex");
Date birthday = rs.getDate("birthday");
String hobbys = rs.getString("hobbys");
String des = rs.getString("des");
//封装对象
user = new User();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
user.setSex(sex);
user.setBirthday(birthday);
user.setHobbys(hobbys);
user.setDes(des);
//装载集合
list.add(user);
}
System.out.println(list);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}

使用jdbc,查询数据库数据,并将其封装为对象输出

原文:https://www.cnblogs.com/newcityboy/p/11349394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!