日期:2014-05-20 浏览次数:20727 次
import java.util.*; import java.sql.*; public class InputStudent { public static void main(String args[]) { Connection con; String sql; Statement stmt; int num; String name,sex; int age; //一、java直接连接Oracle10数据库 try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); } try { con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","system","system"); stmt = con.createStatement(); //写 select语句 sql = " SELECT * FROM S where sex=?"; PreparedStatement stmt0=con.prepareStatement(sql); // stmt0=con.prepareStatement(sql); stmt0.setString(1,"女"); //执行select SQL语句,返回结果集rs,可以看成是游标 ResultSet rs = stmt0.executeQuery(); // ResultSet rs = stmt.executeQuery(sql); //按格式要求打印输出表头部分 System.out.println("\n\n\n\n"); System.out.println(" 全体学生信息表"); System.out.println("--------------------------------"); System.out.println("学号 姓名 性别 年龄"); System.out.println("--------------------------------"); while(rs.next()){ //取当前行数据项的值赋给变量 num = rs.getInt("sno"); name = rs.getString("sname"); sex = rs.getString("sex"); age = rs.getInt("age"); //java将变量的 值按要求的格式输出 System.out.println(num+" "+name+" "+sex+" "+age); } System.out.println("---------------------------------"); stmt.close(); //事务提交, 事务回滚方法是 rollbck() con.commit(); con.close(); } catch(SQLException ex) { System.err.println("**SQLException: " + ex.getMessage()); } } }