结合 JavaBean 和 JDBC,我们可以编写出结构清晰,使用方便的数据库应用程序。
db 类封装了数据库操作,包括建立和关闭连接,以及执行SQL查询操作。
emp类使用db类并针对EMP 表完成了根据工号查询员工资料的功能,并提供了员工姓名的getter方法。
package db;
import java.net.*;
import java.sql.*;
import java.io.*;
public class db {
Connection conn;
Statement stmt;
ResultSet rs;
//数据库连接
public void getConnection(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Hotel;User=sa;Password=sa");
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
//关闭连接
public void closeConnection(){
try{
if (conn != null){
conn.close();
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
//对数据库进行操作
public ResultSet executeQuery(String sql){
rs = null;
try{
getConnection();
if (conn != null){
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
return rs;
}
}
package db;
import java.sql.*;
public class emp extends db {
private String empno;
private String ename;
public emp(String em){
empno = em;
}
//执行Sql语句 对属性ename赋值
public void query(){
try{
String sSql = "select * from emp where empno =" + empno;
ResultSet rs = executeQuery(sSql);
if (rs.next()){
ename = rs.getString("ename");
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
//得到ename
public String getEname(){
return ename;
}
}
package db;
import java.io.*;
import java.sql.*;
public class TestBean {
public static void main(String args[]){
String empno;
emp em;
try{
System.out.println("请输入工号:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
empno = br.readLine();
em = new em(empno);
em.query();
System.out.println("工号为" + empno + "的员工姓名是:" + em.getEname());
em.closeConnection();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}