以前一直用jdbc,没有深入看看,原来jdbc是java自己的接口规范,db厂商按照接口进行开发对应的驱动,jdbc可以获取db中的元信息,执行sql,获取结果,操作db等等。示例如下。
public static void main(String[] args) { try { Class.forName("oracle.jdbc.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:Oracle:thin:DEVH3IMAGE/[email protected]//localhost:1521/orcl"); //获取数据库元信息 DatabaseMetaData data = con.getMetaData(); System.out.println("数据库db名称:"+data.getDatabaseProductName()); System.out.println("数据库db版本"+data.getDatabaseProductVersion()); System.out.println("链接驱动名称:"+data.getDriverName()); System.out.println("db链接url信息:"+data.getURL()); //获取db所有表名称 ResultSet tableset = data.getTables("orcl", "DEVH3IMAGE", null, new String[]{"TABLE"}); System.out.println("db中所有表名"); while (tableset.next()) { System.out.print(tableset.getString("TABLE_NAME") + "\t"); } System.out.println(); ResultSet colset = data.getColumns("orcl", "DEVH3IMAGE", "T_YX_01",null); System.out.println("表T_YX_01中的所有列名"); while (colset.next()) { System.out.print(colset.getString("COLUMN_NAME") + "\t"); } System.out.println(); //同样的 可以获取到db中所有的索引 存储过程 等等信息 System.out.println("====================================="); //设置只读 // con.setReadOnly(true); System.out.println("con is read only ? == "+con.isReadOnly()); //默认是自动提交事务 System.out.println("con is auto commit?==="+con.getAutoCommit()); System.out.println("====================================="); //普通查询 Statement st = con.createStatement(); ResultSet set = st.executeQuery("select * from t_yx_01"); st.close(); //带参数查询 PreparedStatement pst = con.prepareStatement("select * from t_yx_01 where id = ?"); pst.setString(1, "1930128"); ResultSet prSet = pst.executeQuery(); ResultSetMetaData rdata = prSet.getMetaData(); while (prSet.next()) { for (int i = 1; i <= rdata.getColumnCount(); i++) { System.out.print(rdata.getColumnName(i) +":"+ prSet.getString(rdata.getColumnName(i))); System.out.print("\t"); } System.out.println(); } pst.close(); System.out.println("====================================="); con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { //sqlexception中有sql自己的异常信息 System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); }
时间: 2024-10-08 10:32:38