日期:2014-05-16 浏览次数:20681 次
/** * 学生类 * */ public class Student { private int id; private String sex; private String username; private String picName; public String getPicName() { return picName; } public void setPicName(String picName) { this.picName = picName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String toString() { return "id: " + id + " username: " + username + " sex: " + sex; } }
/** * 与Oracle数据库连接 * */ public class OracleConnection { private static String ojdbcURL = "jdbc:oracle:thin:@localhost:1521:xe"; private static String ojdbcDriver = "oracle.jdbc.driver.OracleDriver"; private static String userName = "czc"; private static String password = "netjava"; private static Connection connec; public static Connection getConnec() { if (connec != null) { return connec; } try { Class.forName(ojdbcDriver); connec = DriverManager.getConnection(ojdbcURL, userName, password); System.out.println("与oracle数据库连接成功..."); } catch (Exception e) { System.out.println("与oracle数据库连接失败..."); e.printStackTrace(); } return connec; } }
/** * 数据操作 */ public class StudentDAO { /** * 将学生信息保存到数据库 * * @param stu:学生对象 * @return :是否成功 */ public boolean savaStuMsg(Student stu) { try { // 取得数据库连接对象 Connection connec = OracleConnection.getConnec(); // 写插入SQL String sql = "insert into student(name,sex,picture) values(?,?,?)"; // 得到预编译对象 PreparedStatement pstm = connec.prepareStatement(sql); pstm.setString(1, stu.getUsername()); pstm.setString(2, stu.getSex()); // 创建一个文件输入流对象 FileInputStream fins = new FileInputStream(stu.getPicName()); // 将图片以二制数据保存到数据库 pstm.setBinaryStream(3, fins, fins.available()); pstm.addBatch(); pstm.executeBatch(); System.out.println("学生信息保存成功!"); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 根据学生名字查询学生信息 * * @param username:姓名 * @return */ public Student getStuMsg(String username) { try { Connection connec = OracleConnection.getConnec(); // 注:where后varchar字段必须加'' String sql = "select id,sex from student where name='" + username + "'"; Statement stmt = connec.createStatement(); ResultSet rset = stmt.executeQuery(sql); Student stu = new Student(); if (rset.next()) { stu.setId(rset.getInt("id")); stu.setSex(rset.getString("sex")); stu.setUsername(username); } return stu; } catch (Exception e) { e.printStackTrace(); } return null; }