Java development notes (one hundred forty-eight) through JDBC query data record

Introduced in front of how to manage the database via JDBC, was specifically mentioned Statement provides a method for executeQuery query, why does query so special? This is because other statements to finish a report on the matter, at most, as insert, update, delete and then return the number of records affected, but they are not the same as the select command, the query may return multiple records, and each record It contains multiple fields. This scenario seems more fields of multiple records, regardless of the return value is defined as what type do not very good, and therefore decided to give a separate executeQuery method, the return value of this method is also set to exclusive ResultSet type, indicates that the query method It returns a result set, the results of detailed records go traverse the result set is obtained.
Whereby the recording operation can be divided into the following four steps query:
1, database connection: the step of calling the getConnection method of the DriverManager connection object class is obtained.
2, create performance reports for that connection: the steps of the method call createStatement Connection object to obtain execution report.
3, execute a query command reports: This step calls executeQuery method of reporting the object to execute a query, and the query returns a result set records.
4, loop through all result set of records inside: This step is typically required to be invoked next result set objects method continues to traverse back, i.e. move step by step, the cursor indicating the result set back. Among traversal, you may call other methods to further operation of the result set object, a common method of ResultSet into three categories, as follows:
1, move the cursor
such methods may be current cursor moves to the specified location, including the following methods:
Next : the cursor moves to a record after. This method returns true if not yet moved to the end, and false representation has been moved to the end.
absolute: Move the cursor to the first few records, if the argument is a negative number indicates that the first few reciprocal.
first: the cursor to the first record.
last: Move the cursor to the last record.
previous: The cursor moves to the previous record.
beforeFirst: Move the cursor before the first record.
afterLast: Place your cursor after the last record.
2, the cursor position is determined
such methods may determine whether the current cursor position is at a certain, mainly including the following:
isFirst: the cursor points to the first record.
isLast: the cursor is pointing to the last record.
isBeforeFirst: the cursor is before the first record.
isAfterLast: the cursor is after the last record.
3, the data acquired from the current cursor
Such methods can obtain the value of the record of the current cursor points, when the method of integer parameters, retrieves the specified sequence number field value; when the process parameter is a string, retrieves the specified name field values. The correlation acquisition method are listed below:
the getInt: obtaining field specifies the integer value specified name or number.
getLong: Get the whole field length value specified number or the specified name.
getFloat: Gets the field value of the specified floating-point number or the specified name.
getDouble: Get the specified name or number field specifies the double value.
getString: Get string field value of the specified number or the specified name.
getDate: Get value of the specified field of date specified name or number.

Next, a few examples of specific applications, first of all from teacher to query all records in the table, then in turn connect to the database, create reports connected, execute a query, recycling traverse the result set to obtain field information for each record. This series of query code examples are as follows:

	// query for all records (default sort) 
	Private static void showAllRecord () { 
		String SQL = "from the SELECT * Teacher"; 
		// connect to the database, create reports connected, execute a query 
		try (Connection conn = DriverManager.getConnection (dbUrl , dbUserName, dbPassword); 
				the Statement stmt = conn.createStatement (); 
				the resultSet stmt.executeQuery RS = (SQL)) { 
			the while (rs.next ()) {// loop through all records of the result set which 
				int gonghao = rs.getInt ( "gonghao"); // Get the value of the specified field integer 
				string name = rs.getString ( "name" ); // get the string specified field 
				Date birthday = rs.getDate ( "birthday" ); // Get the value of the specified field date 
				int sex = rs.getInt ( "sex" ); // Get the value of the specified field integer  
				string course = rs.getString ( "course" ); // Get string value of the specified field
				String desc = String.format ( "job number for the% d,% S is the name, date of birth as% s, sex is% s, taught courses for% s. ",
						? gonghao, name, getFormatDate (birthday ), sex == 0 " male": "female", Course,); 
				System.out.println ( "current teacher information:" + desc); 
			} 
		} the catch (SQLException E) { 
			e.printStackTrace (); 
		} 
	}

 

Note MySQL Unavailable date translated into strings of to_char functions, and thus can only be taken to the field value of type Date, which is then converted to a string Java code. Date type method into a string type code as follows:

	// get the date string format specified 
	public static String getFormatDate (a Date DATE) { 
		// create a tool formatted date 
		the SimpleDateFormat the SimpleDateFormat SDF new new = ( "the MM-dd-YYYY"); 
		// specified in accordance with the current date and time the format of the output format date time string 
		return sdf.format (dATE); 
	}

 

This query would then run showAllRecord, observed five log window to full output of the record information as follows.

The current teacher information: The No. 1 name is Zhang, born on 1983-03-03, female gender, taught courses for language. 
The current teacher information: The No. 2, the name is Li, born on 1984-04-04, male gender, taught courses in mathematics. 
The current teacher information: The No. 3, as the name Wang, born on 1985-05-05, female gender, teaching courses in English. 
The current teacher information: job number 4, name is Zhao, born on 1986-06-06, male gender, taught courses for physics. 
The current teacher information: The No. 5, is the name of Liu, born on 1987-07-07, female gender, taught courses for chemistry.

Then increasing in the original sentence sorted, so all records in descending order according to the Birthday field, query code is modified as follows:

	// query all records (in accordance with the birthday reverse) 
	Private static void showAllRecordByBirthday () { 
		String SQL = "Teacher from the Order by the SELECT * Birthday desc"; 
		// connect to the database, create reports connected, execute a query 
		try (Connection conn = DriverManager .getConnection (dbUrl, dbUserName, dbPassword); 
				the Statement stmt = conn.createStatement (); 
				the resultSet stmt.executeQuery RS = (SQL)) { 
			the while (rs.next ()) {// loop through all records a result set inside 
				int gonghao = rs.getInt ( "gonghao") ; // Get the value of the specified field integer 
				string name = rs.getString ( "name" ); // Get string value of the specified field 
				Date birthday = rs.getDate ( "birthday "); // get the date value of the specified field 
				int sex = rs.getInt (" sex " ); // Get the integer value of the specified field 
				String course = rs.getString (" course " ); // Get the specified field string value 
				String desc = String.format (" job number for the% d,% s name is , date of birth is% s, sex is% s, taught courses for% s. ",
						? gonghao, name, getFormatDate (birthday ), sex == 0 " male": "female", Course,); 
				System.out.println ( "current teacher information:" + desc); 
			} 
		} the catch (SQLException E) { 
			e.printStackTrace (); 
		} 
	}

 

With the addition of showAllRecordByBirthday method, run the test again, this time can be seen from the log window with record results show the birthday field in descending order.

The current teacher information: The No. 5, is the name of Liu, born on 1987-07-07, female gender, taught courses for chemistry. 
The current teacher information: job number 4, name is Zhao, born on 1986-06-06, male gender, taught courses for physics. 
The current teacher information: The No. 3, as the name Wang, born on 1985-05-05, female gender, teaching courses in English. 
The current teacher information: The No. 2, the name is Li, born on 1984-04-04, male gender, taught courses in mathematics. 
The current teacher information: The No. 1 name is Zhang, born on 1983-03-03, female gender, taught courses for language.

Sort by adjusting only the sequence returns records, but not the same grouping condition. Because there is a statistical grouping operating conditions, such as count, sum, max functions return the result of the operation only, but the result set depends on the field names of data taking, it is necessary to add an alias after statistical functions, the function corresponding to the calculation result staging to the alias variable. Expressions such as "count (sex) count" said counting result is named by count, i.e. the count value obtained from the cursor to the count field. Here is an example of the teacher table query code field of the packet statistics by sex:

	// query gender grouping. Note that the results give count function like distribution alias 
	Private static void showRecordGroupBySex () { 
		String SQL = "the SELECT Sex, count (Sex) count from Teacher Group by Sex Sex asc by the Order"; 
		// connect to the database, create reports connected performs query 
		the try (Conn = Connection the DriverManager.getConnection (dbUrl, dbUserName, dbPassword); 
				the statement stmt = conn.createStatement (); 
				the ResultSet stmt.executeQuery RS = (SQL)) { 
			the while (rs.next ()) {/ / loops through all the records of the result set which 
				int sex = rs.getInt ( "sex" ); // Get the specified field integer value 
				int count = rs.getInt ( "count" ); // Get the specified field integer value 
				String desc = String.format ( "% s% d teacher has position;", sex == 0 "male": "female", COUNT?); 
				System.out.print (desc);

 

Run a test program showRecordGroupBySex methods really shown the expected correct output statistics log is as follows.

There are two male teacher; there are three female teachers;  



See more Java technology articles " Java Development Notes (order) List of chapters "

Guess you like

Origin www.cnblogs.com/pinlantu/p/11494099.html