需求:
源码查看数据库表所有内容,将其封装为集合对象
[Java] 纯文本查看 复制代码 // 配置文件[/align]
[align=left][size=14px]
[/size][/align]
[align=left]url=jdbc:mysql://localhost:3306/** //表名称[/align]
[align=left]user= *** //账号[/align]
[align=left]password= *** //密码[/align]
[align=left]driver=com.mysql.jdbc.Driver
[Java] 纯文本查看 复制代码 // 工具类
public class JDBCUILTS1 {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
Properties p = new Properties();
p.load(JDBCUILTS1.class.getClassLoader().getResourceAsStream("jdbc.properties"));
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
driver = p.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接 返回连接对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 抛异常
public static void close(Connection con, Statement st) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement st, ResultSet rs) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
[Java] 纯文本查看 复制代码 // Users 类
public class Users {
private int id;
private String name;
private int age;
@Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public Users() {
}
public Users(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
[Java] 纯文本查看 复制代码 // 测试类
public class Test01 {
// 获取一个表对象将其封装为集合 源码 格式
public static void main(String[] args) {
Connection con = null;
PreparedStatement prep = null;
ResultSet rs = null;
List<Users> list= null;
try {
con = JDBCUILTS1.getConnection();
prep = con.prepareStatement("SELECT * FROM users");
rs = prep.executeQuery();
list = new ArrayList<>();
while (rs.next()) {
list.add(new Users(rs.getInt("uid"),rs.getString("uname"),rs.getInt("uage")));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUILTS1.close(con,prep,rs);
}
for (Users users : list) {
System.out.println(users);
}
}
}
一个简单的小案例,
|
|