Recommended tutorial: java tutorial
1. Loading Driver
Before connecting to the database, you need to load the database driver to the JVM (Java Virtual Machine). This requires the static method forName(String className) of the java.lang.Class class. ) implementation.
For example:
//加载Oracle的驱动 try{ Class.forName("oracle.jdbc.OracleDriver"); }catch(ClassNotFoundException e){ System.out.println("找不到程序驱动类,加载驱动失败!"); e.printStackTrace(); }
After successful loading, the instance of the driver class will be registered in the DriverManager class.
2. Create a database connection
## If you want to connect to the database, you need to ask java.sql.DriverManager Request and obtain the Connection<strong></strong> object, which represents a database connection.
Use DriverManager'sgetConnection(url,uname,upass)<strong></strong>Pass in the path to the database, username, and password to get a connection
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.31.50:8080:orcl","uname","upass");
3. Create a Statement
To execute a SQL statement, you must obtain a java.sql.Statement instance, Statement instance Divided into the following 3 types:
1. Execute static statements, usually implemented through Statement instances.
Statement st = conn.createStatement();
2. Execute dynamic statements, usually implemented through PreparedStatement.
PreparedStatement ps = conn.prepareStatement(sql);
3. Execute the database stored procedure. Usually implemented through CallableStatement
CallableStatement cs = conn.prepareCall("{CALL demoSp(?,?)}");
4. Execute sql statement
ResultSet executeQuery(sql) <span style="font-size: 14px;"></span>
Suitable for traversing multiple results, inserting into a set, and returning a result set. You can use .next to traverse the object and use getString("field name") to obtain the field value
int executeUpdate(sql ) Applicable to Update, insert or delete statements and sqlDDL statements, such as creating tables and deleting tables, etc., returning the number of changed items
5. Close JDBC Object
##The closing order must be opposite to the declaration order 1.Close the record set The above is the detailed content of 5 steps to connect to the database using jdbc. For more information, please follow other related articles on the PHP Chinese website!
2.Close the statement 3.Close the connection objectif(rs != null){
rs.close();
}