首页 > 经验记录 > JDBC_ORM

JDBC_ORM

ORM=Object Relationship Database Mapping 对象和关系数据库的映射 简单说,一个对象,对应数据库里的一条记录
//账务类、还有些GetSet方法和toString方法,就懒得贴了
public class ZhangWu
private int id;
private String zname;
private double zmoney;


public class MyJDBC_ORM {
public static void main(String[] args) {
List<ZhangWu> list = get();
for (ZhangWu zw : list) {
System.out.println(zw);
}
}
public static List<ZhangWu> get() {
List<ZhangWu> list = new ArrayList<>();
ZhangWu zw = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (Connection c = DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/mybase?characterEncoding=UTF-8”,
“root”, “614”); Statement s = c.createStatement();) {
//获取表的行总数
String sql = “SELECT COUNT(*) FROM product”;
ResultSet resultSet = s.executeQuery(sql);
int i = 0;
while (resultSet.next()) {
i = resultSet.getInt(1);
}
//遍历表
for (int id = 1; id <= i; id++) {
String sql2 = “select * from zhangwu where id=” + id;
ResultSet resultSet2 = s.executeQuery(sql2);
//把表中对应属性的值取出来赋值给zw对象
if (resultSet2.next()) {
zw = new ZhangWu();
String setString = resultSet2.getString(2);
double setDouble = resultSet2.getDouble(3);
zw.setZname(setString);
zw.setZmoney(setDouble);
zw.setId(id);
}
if (zw != null) {
list.add(zw);
zw = null;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}

运行结果:
ZhangWu{id=1, zname=’吃饭支出’, zmoney=247.0}
ZhangWu{id=2, zname=’工资收入’, zmoney=12345.0}
ZhangWu{id=3, zname=’服装支出’, zmoney=1000.0}
ZhangWu{id=4, zname=’吃饭支出’, zmoney=325.0}
ZhangWu{id=5, zname=’股票收入’, zmoney=8000.0}
ZhangWu{id=6, zname=’打麻将支出’, zmoney=8000.0}
ZhangWu{id=7, zname=’服装支出’, zmoney=5000.0}

           


CAPTCHAis initialing...
EA PLAYER &

历史记录 [ 注意:部分数据仅限于当前浏览器 ]清空

      00:00/00:00