import java.sql.*; public class TestJDBC { public static void main(String[] args) throws Exception{ //1. Load the Driver //->1 Class.forName()|Class.forNmae().newInstance()|new DriverName() //->2 实例化时自动向DriverManager注册,不需要显示调用DriverManager.registerDriver方法 Class.forName("oracle.jdbc.driver.OracleDriver"); //new oracle.jdbc.driver.OracleDriver(); //2. Connect to the DataBase //-> DriverManager.getConnection() Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1522:ORCL", "scott","tiger"); //3. Execute the SQL //->1 Connection.createStatement() //->2 Statement.executeQuery() //->3 Statement.executeUpdate() Statement stat=conn.createStatement(); ResultSet rs=stat.executeQuery("select * from emp"); //4. Retrieve the result data //-> 循环取得结果 while(rs.next()) while(rs.next()) { //5. Show the result data //->将数据库中的各种烈性转换为Java中的类型(getXXX)方法 System.out.println(rs.getString("ENAME")); System.out.println(rs.getString("JOB")); } //6.Close //-> close the ResultSet/ close the statement /close the connection rs.close(); stat.close(); conn.close(); } }
下面是mysql时的情况,稍微一点点不同。
Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test"); PreparedStatement pstat=conn.prepareStatement("select * from member where mid=?"); pstat.setString(1, id); ResultSet rs=pstat.executeQuery(); if(rs.next()) { rs.close(); conn.close(); return "false"; }获取mysql端口号的方法:
mysql> show variables like 'port'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 3306 | +---------------+-------+ 1 row in set (0.00 sec) mysql>