创建Bean查询数据库代码实现
时间: 2023-10-28 15:06:31 浏览: 57
一种面向对象的Java Bean查询方法的实现
以下是一个简单的Java代码示例,用于创建一个Bean类并从数据库中查询数据:
1.创建Bean类
public class Student {
private int id;
private String name;
private int age;
private String gender;
// 构造函数
public Student(int id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
// Getter和Setter方法
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;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
2.查询数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDao {
// JDBC驱动器和数据库URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
// 数据库用户名和密码
static final String USER = "root";
static final String PASS = "123456";
public List<Student> getAllStudents() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Student> students = new ArrayList<Student>();
try {
// 注册JDBC驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
String sql = "SELECT id, name, age, gender FROM students";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
Student student = new Student(id, name, age, gender);
students.add(student);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 清理资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
return students;
}
}
3.使用查询
public class Test {
public static void main(String[] args) {
StudentDao dao = new StudentDao();
List<Student> students = dao.getAllStudents();
for (Student student : students) {
System.out.println(student.getId() + ", " + student.getName() + ", " + student.getAge() + ", " + student.getGender());
}
}
}
以上代码将从数据库中检索所有学生,并将其打印到控制台。您可以根据需要进行修改以满足您的具体要求。
阅读全文