Java的JDBC的select练习
先创个emp文件包,保存emp文件。这些属性都是要查询的表的属性
public class Emp {
private int id;
private String name;
private int job_id;
private double salary;
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
", job_id=" + job_id +
", salary=" + salary +
'}';
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getJob_id() {
return job_id;
}
public void setJob_id(int job_id) {
this.job_id = job_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
然后主文件写代码
javaimport java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBC08 {
public static void main(String[] args) throws SQLException {
List<Emp> list=new JDBC08().finfAll();
System.out.println(list);
}
public List<Emp> finfAll () throws SQLException {
Connection con = null;
Statement s = null;
ResultSet rs = null;
List<Emp> list = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:///hsp_db02", "root", "011012");
String sql = "select * from emp";
s = con.createStatement();
rs = s.executeQuery(sql);
Emp emp = null;
list = new ArrayList<Emp>();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int job_id = rs.getInt("job_id");
double salary = rs.getDouble("salary");
emp = new Emp();
emp.setId(id);
emp.setJob_id(job_id);
emp.setName(name);
emp.setSalary(salary);
list.add(emp);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
if (s != null) {
s.close();
}
if (rs != null) {
rs.close();
}
return null;
}
}
|