MySQL是一個(gè)常用的關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),它可以存儲(chǔ)和管理大量的數(shù)據(jù)。JavaBean是一個(gè)標(biāo)準(zhǔn)的Java類,通常用于封裝業(yè)務(wù)邏輯和數(shù)據(jù)。MySQL和JavaBean可以結(jié)合使用,實(shí)現(xiàn)Java應(yīng)用程序與數(shù)據(jù)庫(kù)之間的數(shù)據(jù)交互。
下面是一個(gè)使用JavaBean和MySQL的代碼示例:
import java.sql.*; import java.util.ArrayList; import java.util.List; public class StudentDAO { private Connection conn; public void connect() { try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC"; String user = "root"; String pwd = "123456"; conn = DriverManager.getConnection(url, user, pwd); } catch (Exception ex) { ex.printStackTrace(); } } public void disconnect() { try { conn.close(); } catch (Exception ex) { ex.printStackTrace(); } } public ListgetStudents() { List students = new ArrayList<>(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student"); while (rs.next()) { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); students.add(student); } rs.close(); stmt.close(); } catch (Exception ex) { ex.printStackTrace(); } return students; } }
上面的代碼示例演示了如何使用JavaBean將數(shù)據(jù)庫(kù)中的數(shù)據(jù)封裝為對(duì)象,并進(jìn)行查詢操作。首先需要連接MySQL數(shù)據(jù)庫(kù),然后通過(guò)查詢語(yǔ)句獲取數(shù)據(jù)結(jié)果集,并將結(jié)果集中的數(shù)據(jù)轉(zhuǎn)換成JavaBean對(duì)象。最后,將JavaBean對(duì)象添加到列表中并返回。