一、表与类的关系
在Java中,我们可以把数据库表和类关联起来,这样就能更方便地操作数据库了。
1. 创建表并插入数据
CREATE TABLE IF NOT EXISTS employee(
id int(11) auto_increment PRIMARY key,
name VARCHAR(22),
age int(4),
money int(20)
);
INSERT into employee VALUES(null,"张三",20,3650);
INSERT into employee VALUES(null,"李四",30,4502);
INSERT into employee VALUES(null,"王五",30,3650);
INSERT into employee VALUES(null,"麻子",50,8885);
INSERT into employee VALUES(null,"小红",20,4445);
2. 查询表中数据
接下来,我们可以通过SQL语句查询表中的数据。
二、案例演示
1. 创建一个Employee类
public class Employee {
private int id;
private String name;
private int age;
private int money;
public Employee() {
}
public Employee(int id, String name, int age, int money) {
this.id = id;
this.name = name;
this.age = age;
this.money = money;
}
// 省略其他getter和setter方法...
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", money=" + money +
'}';
}
}
2. PreparedStatement
使用PreparedStatement查询数据,并封装成对象,存入一个集合中。
public class demo1 {
public static void main(String[] args) throws ClassNotFoundException {
ResourceBundle rb = ResourceBundle.getBundle("config/jdbc");
Class.forName(rb.getString("Driver"));
Connection con = null;
PreparedStatement pre = null;
ResultSet rs = null;
List list = new ArrayList<>();
try {
con = DriverManager.getConnection(rb.getString("url"), rb.getString("user"), rb.getString("password"));
String sql = "select * from employee";
pre = con.prepareStatement(sql);
rs = pre.executeQuery(sql);
Employee emp = null;
while (rs.next()) {
emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setAge(rs.getInt("age"));
emp.setMoney(rs.getInt("money"));
list.add(emp);
}
System.out.println(list);
System.out.println("操作完成!");
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
pre.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
三、小结与拓展
通过上面的案例,我们学会了如何将数据库表和Java类关联起来,并通过PreparedStatement查询数据。这是一个非常实用的技能,希望对大家有所帮助。
如果你对Java编程还有其他疑问,欢迎访问趣航编程网,了解更多编程知识。
