我要评分
获取效率
正确性
完整性
易理解

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:

  1. Load the JDBC driver and register the driver.

    Oracle database:

    Class.forName("oracle.jdbc.driver.OracleDriver");

    MySQL database:

    Class.forName("com.mysql.jdbc.Driver");
  2. 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);
  3. Obtain a Statement object.
    Statement sta = conn.createStatement();
    
    PreparedStatement pstm = conn.prepareStatement();
  4. 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);
  5. Operate the result set returned by the SQL statements.
                      while(rs.next()){
    
    System.out.println(rs.getString("name"));
    
    //------------------
    
    }
  6. 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();