1.How to establish a databse connection using JDBC
1).Register JDBC Driver -DriverManager.registerDriver()
1 try{ 2 Driver myDriver = new oracle.jdbc.driver.OracleDriver(); 3 DriverManager. registerDriver(myDriver); 4 }catch(ClassNotFoundException ex){ 5 System.out.println("Error: unble to load driver class!"); 6 System.exit(1); 7 }
2).Create Connection Object -DriverManager.getConnection()
Three overloaded DriverManager.getConnection() methods
- getConnection(String url)
- getConnection(String url, Properties prop)
- getConnection(String url, String user, String password)
URL is an address that points to your database
RDBMS JDBC driver name URL format MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName
1 String url ="jdbc:oracle:thin:username/password@database:portnum" 2 Connection con = DriverManager.getConnection(url); 3 4 String url = "jdbc.oracle.thin:@localhost:1522:xe"; 5 Properties info = new Properties(); 6 info.put ("user","username"); 7 info.put("password","password"); 8 Connection con = DriverManager.getConnection(url,info); 9 10 String url = "jdbc:oracle:thin:@localhost:1522:xe" 11 String USER = "username"; 12 String PASS = "password"; 13 Connection con = DriverManager.getConnection(url,USER, PASS);
3).Closing JDBC connection
1 con.close();
There is a whole simple example below:
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultsetTest { static String dburl = "jdbc:oracle:thin:bsdtest/bsdtest@localhost:1522:xe"; public static void main (String[] args) throws SQLException{ Connection con = DriverManager.getConnection(dburl); // Connection con = DriverManager.getConnection // ("jdbc:oracle:thin:@localhost:1522","bsdtest","bsdtest"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select name from person"); while (rs.next()){ System.out.println("name="+rs.getString("name")); } stmt.close(); con.close(); }