The six main steps of JDBC:
- Registration driver
- Get connections
- Gets the Execute SQL statement object
- Execute SQL statement
- Working with result sets
- Close Resource
Oracle URL:
jdbc:oracle:thin:@localhost:1521:SID
jdbc:oracle:thin:@//localhost:1521:SERVICENAME
MySQL URL:
jdbc:mysql://localhost:3306/数据库名称
Thin: small drive, drive mode
localhost native IP address 127.0.0.1
SID: SID of the database
S ERVICENAME
: The SID of the database
Two common ways of connecting
Code:
Package CN.ZHISHENG.TEST.JDBC;Import Oracle.jdbc.driver.OracleDriver;Import java.sql.*;Import java.util.Properties;/** * Created by 10412 on 2016/12/27. * Six Steps of JDBC * Three ways to connect to Oracle in Java */PublicClassjdbctest{PublicStaticvoidMain (string[] args) {Connection connect =Null Statement Statement =Null ResultSet ResultSet =Nulltry {First Step: Register driverFirst way: Class loading (common)Class.forName ("Oracle.jdbc.OracleDriver");The second way: Using the Driver object Driver Driver =New Oracledriver (); Drivermanager.deregisterdriver (driver); Step two: Get the connectionFirst way: Using DriverManager (Common)Connect = Drivermanager.getconnection ("Jdbc:oracle:thin: @localhost: 1521:xe", "Your Oracle database user name", "username password");Second way: Direct use of driver Properties Pro =New Properties (); Pro.put ("User","Your Oracle database user name"); Pro.put ("Password","User name password"); Connect = Driver.connect ("Jdbc:oracle:thin: @localhost: 1521:xe", pro);Test Connect is correct or not System.out.println (connect);Step three: Get the Execute SQL statement objectThe first way: statementstatement = Connect.createstatement ();The second way: prestatement preparedstatement prestate = connect.preparestatement ("SELECT * from tb1_dept where id =?");Fourth step: Execute the SQL statementThe first way:ResultSet = Statement.executequery ("SELECT * from tb1_dept");The second way: Prestate.setint (1,2);1 refers to the first of the SQL statements? , 2 means the first one? Values forResultSet = Prestate.executequery (); Execute Query statementQuery any statement, if there is a result set, return True, no, return false, note that if you insert a piece of data, although there is no result set, return false, but can successfully insert a piece of dataBoolean execute = Prestate.execute (); System.out.println (execute);Fifth step: Working with result setswhile (Resultset.next ()) {int id = resultset.getint ( "id"); String name = resultset.getstring ( "name"); String City = resultset.getstring ( "+name+" +city); //printout result set}} catch (Exception e) {e.printstacktrace ();} finally {//Sixth step: Close resource try {if (Resultset!=null) resultset.close (); if (Statement!=null) statement.close (); if (Connect!=null) connect.close (); catch (SQLException e) {e.printstacktrace ();}} }}
Common ways for Java to connect to an Oracle database