JDBC Programming Guidelines for Java Project Development
Java database connectivity (JDBC) is an API used to execute SQL statements. It consists of a group of classes and interfaces written in Java. It provides unified access to a variety of relational databases, serving as a foundation for building more advanced tools and interfaces. This enables database developers to write database applications that achieve standard-oriented goals while providing interfaces that are simple, strictly defined, and high-performance. The JDBC programming guidelines are as follows:
- Load the JDBC driver and register the driver.
Oracle database:
Class.forName("oracle.jdbc.driver.OracleDriver");MySQL database:
Class.forName("com.mysql.jdbc.Driver"); - Use DriverManager to establish a database connection.
Mysql: String url = "jdbc:mysql://localhost:3306/tarena"; Oracle: String url = "jdbc:oracle:thin:@localhost:1521:tarena"; String name="root"; String pwd ="root"; Connection conn = DriverManager.getConnection(url,name,pwd); - Obtain a Statement object.
Statement sta = conn.createStatement(); PreparedStatement pstm = conn.prepareStatement();
- Execute SQL statements via Statement.
For SELECT statements, the method returns a query result set.
ResultSet rs = sta.executeQuery(String sql);
For INSERT, UPDATE, and DELETE statements, the method returns an integer value representing the number of affected records.
int I = sta.executeUpdate(String sql);
- Operate the result set returned by the SQL statements.
while(rs.next()){ System.out.println(rs.getString("name")); //------------------ } - Call the .close() method to close the database connection and release resources.This step involves calling the close() method of ResultSet, Statement, and Connection.
rs.close(); sta.close(); con.close();
Parent topic: Programming