Five steps for using JDBC and query operations-database programming (2)
Jdbc usage steps
1. Load the jdbc driver.
2. Open the database connection.
3. Create a session and perform basic operations such as adding, deleting, modifying, and querying.
4. process the results
5. Clean up the environment, such as closing the session.
Query operations
First, use the forname method of the Class to instantiate a driver instance.
Then initialize three classes: Connection Statement ResultSet. These three classes are used to establish connections, execute operations, and process results respectively.
DriverManager uses the getConnection method to input three parameters: Database url and user name, and password to obtain the connection instance.
The createStatement method of connection to obtain the Statement instance.
Statement executeQuery method to obtain the ResultSet instance.
Finally, close the resultSet, Sratement, and Connection instances in ascending order.
The Code is as follows:
String sql = "SELECT * FROM tbl_user"; Connection conn = null; Statement st = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", ""); st = (Statement) conn.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { System.out.print(rs.getInt("id")+" "); System.out.print(rs.getString("name")+" "); System.out.print(rs.getString("password")+" "); System.out.print(rs.getString("email")+" "); System.out.println(""); } } catch (Exception e) { e.printStackTrace(); }finally{ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }