Use JDBC to query data from a database.
* ResultSet result set: encapsulates the query results using JDBC.
* 1.Call the executeQuery (SQL) method of the Statement object to obtain the result set.
* 2.The ResultSet returns a data table with a pointer pointing to the front of the first row of the data table,
* You can call the next () method to check whether the next row is valid. If the row is valid, true is returned and the pointer is moved down,
* It is equivalent to the combination of hasNext () and next () Methods of the iterator object.
* 3.When the pointer locates a row, it can be obtained by calling the getXxx (index) method or the getXxx (columnName) method.
* The value of each column. For example, getInt (1) gets the value of the first column, getString ("name") gets the value of the column whose column name is "name"
@ Test public void testResultSet () {// obtain the record of the MERs data table with id = 2, and print Connection = null; Statement statement = null; ResultSet rs = null; try {// 1. obtain Connection connection = JDBCTools. getConnection (); // 2. get Statement statement = connection. createStatement (); // 3. prepare SQL String SQL = "SELECT * FROM MERs WHERE ID = 2"; // 4. run the query to obtain ResultSet rs = statement.exe cuteQuery (SQL); // 5. processing ResultSet while (rs. next () {// rs. get + the corresponding type in the database + (the column alias in the database) int id = rs. getInt ("ID"); String name = rs. getString ("name"); String email = rs. getString ("email"); Date birth = rs. getDate ("birth"); System. out. println (id); System. out. println (name); System. out. println (email); System. out. println (birth) ;}} catch (Exception e) {e. printStackTrace ();} finally {// 6. disable the corresponding resources of the database, JDBCTools. release (rs, statement, connection );}}
The method that is disabled writes an overloaded
This is just the most basic query operation using JDBC. It may not be perfect in the future ~
The above method of querying data from the database using JDBC is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the customer's house.