码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2019-08-14 00:08:55      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:util   exe   集合   遍历   nts   mys   turn   int   pac   

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,查询数据库数据,并将其封装为对象输出

标签:util   exe   集合   遍历   nts   mys   turn   int   pac   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!