1 import java.io.FileInputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 import java.util.Properties; 10 11 public class JdbcDemo { 12 //创建对象关联配置文件 13 private Properties pro = new Properties(); 14 private String driver; 15 private String url; 16 private String user; 17 private String psw; 18 19 public JdbcDemo(){ 20 try { 21 //通过反射获取数据流 22 pro.load(this.getClass().getResourceAsStream("MyOrcDb.properties")); 23 //获取配置文件数据 24 this.setDriver(pro.getProperty("driver")); 25 this.setUrl(pro.getProperty("url")); 26 this.setUser(pro.getProperty("user")); 27 this.setPsw(pro.getProperty("psw")); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 } 32 33 private void minSalName(){ 34 35 //连接数据库 36 try { 37 Class.forName(driver); 38 //获取连接 39 Connection con; 40 con = DriverManager.getConnection(url,user,psw); 41 //sql语句载入数据库 42 Statement st = con.createStatement(); 43 //读取各部门最低工资名单 44 //关闭数据库 45 String sql = "SELECT emp.deptno,emp.ename,emp.sal from emp," 46 + "(SELECT deptno,min(sal) minSal from emp GROUP BY deptno) a " 47 + "where emp.deptno = a.deptno " 48 + "and emp.sal = a.minsal"; 49 //获得结果集 50 ResultSet rst = st.executeQuery(sql ); 51 //获得结果集的列数 52 int n = rst.getMetaData().getColumnCount(); 53 //遍历结果集 54 String str = ""; 55 for(;rst.next();){ 56 for(int i=1;i<=n;i++){ 57 str += rst.getString(i)+"\t"; 58 } 59 str += "\n"; 60 } 61 System.out.println(str); 62 //关闭JDBC(先开后关) 63 rst.close(); 64 st.close(); 65 con.close(); 66 } catch (ClassNotFoundException e) { 67 e.printStackTrace(); 68 } 69 catch (SQLException e) { 70 e.printStackTrace(); 71 } 72 } 73 public String getDriver() { 74 return driver; 75 } 76 public void setDriver(String driver) { 77 this.driver = driver; 78 } 79 public String getUrl() { 80 return url; 81 } 82 public void setUrl(String url) { 83 this.url = url; 84 } 85 public String getUser() { 86 return user; 87 } 88 public void setUser(String user) { 89 this.user = user; 90 } 91 public String getPsw() { 92 return psw; 93 } 94 public void setPsw(String psw) { 95 this.psw = psw; 96 } 97 public static void main(String[] args) { 98 JdbcDemo jdbc = new JdbcDemo(); 99 jdbc.minSalName(); 100 } 101 102 }
时间: 2024-12-28 15:23:05