This article describes the implementation method of using JDBC to connect to the database in Java. It is a very practical and important skill in Java database programming. Share it with everyone for your reference. The details are as follows:
JDBC (Java Data Base Connectivity) database connection, usually we use JDBC when we write web applications or java applications to connect to the database. The general steps to connect to a database using JDBC are:
1. Load the driver
Class.forName(driver);
2. Create a connection object
Connection con = DriverManager.getConnection(url,username,password);
3. Create sql statement execution object
4. Execute sql statement
5. Process the execution results
6. Close the relevant connection objects (in the reverse order of declaration)
The following is an example of establishing a connection to a MySQL database. The process for other databases is similar:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DBConnection{public static void main(String[] args){ String driver = "com.mysql.jdbc.Driver";//localhost refers to the local machine, you can also use the local IP address instead, 3306 is the default port number of the MySQL database, "user" is the name of the database to be connected String url = "jdbc:mysql ://localhost:3306/user";//Fill in the username and password of the database String username = "test";String password = "test";String sql = "select * from user";//Write the sql statement to be executed, here is to query the information of all users from the user table try{Class.forName(driver);//Load the driver, here use the implicit registration driver Program method}catch(ClassNotFoundException e){e.printStackTrace();}try{Connection con = DriverManager.getConnection(url,username,password);//Create connection object Statement st = con.createStatement();//Create the sql execution object ResultSet rs = st.executeQuery(sql);//Execute the sql statement and return the result set while(rs.next())//Traverse the result set and output {System. out.println("username: "+rs.getString(1));//Get data through column labels System.out.println("useradd: "+rs.getString("useradd"));//Get data through column names System.out.println("userage: "+rs.getInt("userage"));}//Close related objects if( rs != null){try{rs.close();}catch(SQLException e){e.printStackTrace();}}if(st != null){try{st.close();}catch(SQLException e){e.printStackTrace();}}if(con !=null){try{con.close();}catch(SQLException e){e .printStackTrace();}}}catch(SQLException e){e.printStackTrace();}}}
I believe that what this article describes has certain reference value for everyone's Java database programming.