afrag |
|
|||
記錄學(xué)習(xí)和成長的歷程 |
日歷
統(tǒng)計
導(dǎo)航常用鏈接留言簿隨筆分類隨筆檔案文章檔案搜索積分與排名
最新評論
閱讀排行榜評論排行榜 |
有同事問到在程序中怎樣知道數(shù)據(jù)庫表中那些字段是主鍵。當(dāng)時不知道,晚上回來看了看JDK的文檔。 在使用JDBC來查詢數(shù)據(jù)庫的時候,通常的步驟是: 1. 注冊驅(qū)動程序 2. 獲取數(shù)據(jù)庫連接 3. 執(zhí)行查詢語句 4. 關(guān)閉連接。 在獲得數(shù)據(jù)庫連接后,就可以通過getMetaData()方法來獲取DatabaseMetaData;然后通過DatabaseMetaData的getPrimaryKeys ()方法來獲取主鍵的信息。 下面是我做的示例程序,該程序在JBuilder2005+oracle8i下通過: import javax.sql.*; public class TestJDBC { public TestJDBC() { } public static void main(String[] args) throws SQLException { Connection con = null; Statement st = null; ResultSet rst = null; try{ //注冊數(shù)據(jù)庫驅(qū)動程序 Class.forName("oracle.jdbc.driver.OracleDriver"); //獲取數(shù)據(jù)庫連接 con = DriverManager.getConnection("jdbc:oracle:thin:@10.60.203.80:1521:TestDB","123","123"); //獲取主鍵信息 rst = con.getMetaData().getPrimaryKeys(null,null,"USER"); //打印主鍵信息 if (!rst.isAfterLast()) { rst.next(); System.out.println(rst.getString("TABLE_NAME") + " " + rst.getString("COLUMN_NAME")); } } catch (Exception e){ System.out.println(e.getLocalizedMessage()); } finally{ try{ //關(guān)閉連接 if (rst != null) rst.close(); if (con != null) con.close(); } catch (SQLException e){ throw e; } } } } 上面的程序中,在獲取主鍵信息的時候,語句 rst = con.getMetaData().getPrimaryKeys(null,null,"USER"); 用來獲取主鍵信息。關(guān)于該函數(shù)的詳細信息,請參閱JDK的文檔。這里要說的是,在測試中發(fā)現(xiàn)第三個參數(shù)(數(shù)據(jù)庫表名)是大小寫敏感的,如果寫成user是查不到結(jié)果的。
評論:
|
![]() |
|
Copyright © afrag | Powered by: 博客園 模板提供:滬江博客 |