JDBC的操作
Oracle数据库连接:
1 import java.sql.*; 2 public class TestJDBC { 3 4 public static void main(String[] args) throws Exception { 5 Class.forName("oracle.jdbc.OracleDriver"); 6 Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tigger"); 7 Statement stmt = conn.createStatement(); 8 ResultSet rs = stmt.executeQuery("select * from emp"); 9 while(rs.next()) { 10 System.out.println(rs.getString("deptno")); 11 } 12 rs.close(); 13 stmt.close(); 14 conn.close(); 15 } 16 17 }
MySQL:
select user,host,password from mysql.user;
通过JDBC链接MySQL数据库
1 import java.sql.*; 2 3 public class TestJDBC { 4 5 public static void main(String[] args) { 6 try { 7 Class.forName("com.mysql.jdbc.Driver").newInstance(); 8 } catch (Exception ex) { 9 // handle the error 10 } 11 Connection conn = null; 12 Statement stmt = null; 13 ResultSet rs = null; 14 try { 15 conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?" 16 + "user=root&password=root"); 17 stmt = conn.createStatement(); 18 rs = stmt.executeQuery("select * from dept"); 19 while (rs.next()) { 20 System.out.println(rs.getString("loc")); 21 } 22 23 } catch (SQLException ex) { 24 // handle any errors 25 System.out.println("SQLException: " + ex.getMessage()); 26 System.out.println("SQLState: " + ex.getSQLState()); 27 System.out.println("VendorError: " + ex.getErrorCode()); 28 } finally { 29 // it is a good idea to release 30 // resources in a finally{} block 31 // in reverse-order of their creation 32 // if they are no-longer needed 33 if (rs != null) { 34 try { 35 rs.close(); 36 } catch (SQLException sqlEx) { 37 } // ignore 38 39 rs = null; 40 } 41 if (stmt != null) { 42 try { 43 stmt.close(); 44 } catch (SQLException sqlEx) { 45 } // ignore 46 47 stmt = null; 48 } 49 } 50 51 } 52 53 }