资源描述
文档供参考,可复制、编制,期待您的好评与关注! JAVA数据库取数据万用方法2009-03-21 12:24/* To change this template, choose Tools | Templates* and open the template in the editor.*/package util;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.util.Vector;import java.util.logging.Level;import java.util.logging.Logger;/* author Administrator*/public class DBAccess private static String Dr = com.microsoft.jdbc.sqlserver.SQLServerDriver; private static String url = jdbc:microsoft:sqlserver:/localhost:1433;databaseName=BookShop;/创建Connection对象 public Connection getConnection() Connection conn = null; try Class.forName(Dr);/创建驱动 conn = DriverManager.getConnection(url, 用户名, 密码);/创建数据库连接 catch (ClassNotFoundException ex) Logger.getLogger(DBAccess.class.getName().log(Level.SEVERE, null, ex); catch (SQLException ex) Logger.getLogger(DBAccess.class.getName().log(Level.SEVERE, null, ex); return conn; /查询方法/传入一个sql语句,返回一个Vector集合 public Vector inquiryFacility(String sql) Connection con; Vector vc = new Vector(); ResultSet rs = null; PreparedStatement st = null; /得到数据库连接对象 con = this.getConnection(); /判断是否为空 if (con != null) try st = con.prepareCall(sql); /执行sql语句 rs = st.executeQuery(); while (rs.next() ResultSetMetaData rsmd = rs.getMetaData(); /获得一行中有多少个字段 int numberOfColumns = rsmd.getColumnCount(); Vector vt = new Vector(); /循环便利每一行的值 for (int i = 1; i = numberOfColumns; i+) /将每一个字段的值加入vt集合中 vt.add(rs.getObject(i); /将获得的每一行的集合放到vc集合中 vc.add(vt); catch (SQLException ex) Logger.getLogger(DBAccess.class.getName().log(Level.SEVERE, null, ex); finally try /关闭连接 rs.close(); st.close(); con.close(); catch (SQLException ex) Logger.getLogger(DBAccess.class.getName().log(Level.SEVERE, null, ex); else System.out.println(数据库连接错误); /返回一个Vector对象 return vc; public static void main(String args) /传入sql语句,获得查询结果 Vector vc = new DBAccess().inquiryFacility(sql语句); /取出每一行数据 for(int i = 0;i vc.size(); i+) /取出每一列数据 for(int j = 0;j (Vector)vc.get(i).size();j+) System.out.print(t+(Vector)vc.get(i).get(j); System.out.println(); 运行的适合别忘了加载驱动包,上面的驱动是针对SQL server2005来用的,如果你用的是MySQL、oracle请把上面的驱动改掉,取出来的数据是Object类型的,别忘了转换类型!这个方法是我自己写的,有什么不足的地方,请把你宝贵的意见提出来!谢谢3 / 3
展开阅读全文