To connect to a database step:
1. Registration driver (only once)
2. Establishing a connection (Connection)
3. Create a statement that executes SQL (Statement)
4. Execute the statement
5. Processing execution Results (RESULTSET)
6. Releasing Resources
Example:
Public voidConnectionoracle ()throwssqlexception{Connection conn =NULL; // database connection PreparedStatement PS =NULL; // Precompiled Statement Object ResultSet rs =NULL; // result set object Try { //Registering (Loading) Oracle Drivers class.forname ("Oracle.jdbc.driver.OracleDriver");
Class.forName ("Com.mysql.jdbc.Driver");register (load) MySQL driver
String url = "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL";
String url = "Jdbc:mysql://127.0.0.1:3306/mybatis";
String url = "Jdbc:mysql://localhost:3306/mybatis";
String User= "Scott"; String Password= "Tiger"; Conn = drivermanager.getconnection (url, user, password); String SQL= "Select ename from emp where job = ' Clerk '"; PS=conn.preparestatement (SQL); RS=Ps.executequery (); while(Rs.next ()) {System.out.println ("Ename is:" + rs.getstring ("ename")); } System.out.println ("[Email protected]@@"); } Catch(ClassNotFoundException e) {e.printstacktrace (); }finally {
try {if (rs! = null) {Rs.close ();}}
finally {
try {if (PS! = null) {Ps.close ();}}
finally {if (conn! = null) {Conn.close ();}
}
}
}
}
If sql= "SELECT COUNT (*) from items";
When it is used
while (Rs.next ()) {
System.out.println (Rs.getint (1));
}
JDBC--001--General way to create a database connection (ORACLE/MYSQL)