Six steps to create a JDBC

JDBC API library contains commonly used in the database:

  • Connect to the database
  • Create a SQL or MySQL statement
  • Or execute SQL queries in MySQL database
  • View and modify data records in the database

Create a JDBC application

Establish a JDBC application, this tutorial Java to connect to MySQL as an example, is divided into six steps:

1. Import Package

JDBC database containing the desired program in the program category. In most cases, the use import java.sql.*is sufficient, as follows:

//STEP 1. Import required packages
import java.sql.*;

2. Register JDBC Driver

Needed to initialize the driver, so you can open a communication with the database. The following is a code snippet to achieve this goal:

//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

3. Open a connection

Used DriverManager.getConnection()to create a method of Connectionan object that represents a physical database connection, as follows:

//STEP 3: Open a connection
//  Database credentials
static final String USER = "root";
static final String PASS = "pwd123456";
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

 

4. Execute a query

Requires the use of a type Statementor PreparedStatementobject and submit a statement to the SQL database query is executed. as follows:

//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

If you want to execute a SQL statement: UPDATE, INSERTor DELETEstatements, you need the following code fragment:

//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "DELETE FROM Employees";
ResultSet rs = stmt.executeUpdate(sql);

 

The concentrated extract data from the result

This step demonstrates how to obtain data from the database query results. It can be used an appropriate ResultSet.getXXX()method to retrieve the data as follows:

//STEP 5: Extract data from result set
while(rs.next()){
    //Retrieve by column name
    int id  = rs.getInt("id");
    int age = rs.getInt("age");
    String first = rs.getString("first");
    String last = rs.getString("last");

    //Display values
    System.out.print("ID: " + id);
    System.out.print(", Age: " + age);
    System.out.print(", First: " + first);
    System.out.println(", Last: " + last);
}

 

6. clean up environmental resources

After using JDBC data interoperability and data in the database, should explicitly close all database resources in order to reduce the waste of resources, to rely on the JVM's garbage collection as follows:

//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();



Guess you like

Origin www.cnblogs.com/henrypaul/p/12360453.html