JDBC高级查询实例
来源:互联网 发布:c语言数组遍历 编辑:程序博客网 时间:2024/06/12 12:09
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import com.neusoft.java275.chaper10.Student;public class FirstJDBC{ public static void main(String[] args) throws ClassNotFoundException, SQLException { Connection con = null; //Statement stmt = null; PreparedStatement prestmt=null; ResultSet rs = null; List<Student> list = new ArrayList<Student>(); try { Class.forName("oracle.jdbc.driver.OracleDriver");//加载驱动 con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.137.23:1521:unieap", "scott", "tiger");//连接数据库 //stmt = con.createStatement(); //操作数据库 prestmt=con.prepareStatement("select id,name from student where id=?"); //rs = stmt.executeQuery("select id,name from student where id=1");//执行SQL prestmt.setString(1, "2"); rs =prestmt.executeQuery(); ResultSetMetaData metaData=rs.getMetaData(); StringBuilder stringBuilder=new StringBuilder(32); for(int i=1;i<=metaData.getColumnCount();i++) { stringBuilder.append(metaData.getColumnName(i)); stringBuilder.append(" "); } System.out.println(stringBuilder.toString()); while (rs.next()) {//获取结果 int id = rs.getInt("id");//get id column String name = rs.getString("name"); Student student = new Student(id, name, null, 0); list.add(student); } for (Student student1 : list) { System.out.println(student1.getId() + "," + student1.getName()); } } catch (ClassNotFoundException e) { System.out.println("加载驱动Error"); throw e; } catch (SQLException e) { System.out.println("access database error"); throw e; } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } }// if (stmt != null)// {// try// {// stmt.close();// }// catch (SQLException e)// {// e.printStackTrace();// }// } if (prestmt != null) { try { prestmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }}