JDBC (database connection and use), jdbc database
1. Introduction to JDBC
Quick Start
Preparations:Ii. encoding stage:
Database connection process detailsIn development, the reflection method is generally used to register the driver. There are two advantages: 1. the driver is registered only once, improving efficiency. 2. You can extract the driver's full-outsourcing name into the configuration file for further maintenance.
Connect to database
Format: Connection conn = DriverManager. getConnection (url, name, password );
Url: Database address
Format: Master Protocol: Sub-Protocol: // host: Port/Database Name
Example: jdbc: mysql: // localhost: 3306/jdbc
Note: If the host is a local host port and the default port is 3306, it can be abbreviated as jdbc: mysql: // jdbc.
Name: User name
Password: password
Create Statement to execute SQL statements
ResultSet result set
The ResultSet encapsulates the data returned by the query. The ResultSet encapsulates the query results and can be viewed as a table with a cursor (pointer) maintained internally. The cursor points to the first data, when we execute the next () method, the cursor will look down to see if there is a next data, if there is a next method, it will return true, and the cursor moves down a row, if there is no next data, return false, when the cursor points to a row, you can use the getXXX () method to obtain data under a field in the row. How to retrieve data in ResultSet
1. First, use the next () method to check whether the result set has the next row of data. If yes, true is returned and the result set pointer is moved to the next row. Otherwise, false is returned.
2. when the next () method returns true, you can use the ResultSet object method to retrieve data, for example, getInt () getString () getDate () getObject () parameters in parentheses: field name (the name of the queried field)
// Create a ResultSet object to receive query results
ResultSet rs=stem.executeQuery("select * from user");
// Retrieve data using next () and various get Methods
while(rs.next())
{
System.out.print("id:"+rs.getInt("id"));
System.out.print(",username:"+rs.getString("username"));
System.out.print(",password:"+rs.getString("password"));
//.....
System.out.println();
}
Close Resources
Principle: all resources related to the database are closed from small to large.
RresultSet ----> Statement -------> Connection
From Weizhi note (Wiz)