jdbc简单封装
实体类
package org.example;public class account {private int id;private String name;private double balance;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 double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}@Overridepublic String toString() {return "account{" +"id=" + id +", name='" + name + '\'' +", balance=" + balance +'}';}
}
数据库读取数据并封装
package org.jdbc;import org.example.account;import java.sql.*;
import java.util.ArrayList;
import java.util.List;public class jdbcdemo3 {public static void main(String[] args){List<account> list = new jdbcdemo3().findall();System.out.println(list);}public List<account> findall(){Connection connection = null;Statement statement = null;ResultSet resultSet =null;List<account> list = null;try {//兼容低版本mysqlClass.forName("com.mysql.jdbc.Driver");String query = "select * from account";connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","password");statement = connection.createStatement();resultSet = statement.executeQuery(query);account acc = null;list = new ArrayList<>();while (resultSet.next()){int id = resultSet.getInt("id");String name = resultSet.getNString("name");double balance = resultSet.getDouble("balance");System.out.println(id +"----"+name+"-----"+balance);acc = new account();acc.setId(id);acc.setName(name);acc.setBalance(balance);list.add(acc);}}catch (ClassNotFoundException e) {throw new RuntimeException(e);} catch (SQLException e) {throw new RuntimeException(e);}finally {if(resultSet != null){try {resultSet.close();} catch (SQLException e) {throw new RuntimeException(e);}}if(statement != null){try {statement.close();} catch (SQLException e) {throw new RuntimeException(e);}}if(connection != null){try {connection.close();} catch (SQLException e) {throw new RuntimeException(e);}}}return list;}
}